powershell-command.mjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const POWERSHELL_COMMON_ARGS = ["-NoLogo", "-NoProfile", "-NonInteractive"];
  2. const WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP = [
  3. "$ErrorActionPreference='Stop';",
  4. "try{",
  5. "$zcodeSecurityModule=[IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Security','Microsoft.PowerShell.Security.psd1');",
  6. "Import-Module -Name $zcodeSecurityModule -Force -ErrorAction Stop;",
  7. "}catch{",
  8. "[Console]::Error.WriteLine(('Windows PowerShell Security module load failed: {0}' -f $_.Exception.Message));",
  9. "exit 26;",
  10. "};",
  11. ].join("");
  12. function encodeUtf8Value(value) {
  13. return Buffer.from(value, "utf8").toString("base64");
  14. }
  15. export function createEncodedPowerShellArgs(script, values = []) {
  16. // Windows PowerShell 5.1 会把普通 `-Command` 后续 argv 拼回命令文本,
  17. // 不会把它们注入 `$args`。动态值先单独编码,再放进 `-EncodedCommand`,同时避免
  18. // Program Files 空格、引号或分号被 PowerShell 二次解析成脚本内容。
  19. const valueBindings = values
  20. .map(
  21. (value, index) =>
  22. `$zcodeArg${index}=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodeUtf8Value(value)}'));`,
  23. )
  24. .join("");
  25. const encodedCommand = Buffer.from(`${valueBindings}${script}`, "utf16le").toString("base64");
  26. return [...POWERSHELL_COMMON_ARGS, "-EncodedCommand", encodedCommand];
  27. }
  28. export function createWindowsPowerShellSecurityArgs(script, values = []) {
  29. // 由 pwsh 启动的 Node 会继承 PowerShell 7 的 PSModulePath,随后再启动
  30. // Windows PowerShell 5.1 时可能错误发现不兼容的 Security 模块。直接从当前
  31. // powershell.exe 的 PSHOME 加载系统模块,避免把外部环境变量当作模块信任根。
  32. return createEncodedPowerShellArgs(`${WINDOWS_POWERSHELL_SECURITY_BOOTSTRAP}${script}`, values);
  33. }