从标准输入解释脚本时如何将参数传递给 powershell 命令

How to pass parameters to powershell command when interpreting script from standard input

我是 运行 ssh 上的 powershell 脚本 ssh user@host "powershell -Comand - < script.ps1。只要我开始传递参数,它就会按预期工作。

当我把它写成 powershell -Command - my args 时它失败了(如文档所述) '-' was specified with the -Command parameter; no other arguments to -Command are permitted.

相反 powershell my args -Command - 它失败了:

The term 'my' is not recognized as the name of a cmdlet, function, script file,
 or operable program. Check the spelling of the name, or if a path was included
, verify that the path is correct and try again.
At line:1 char:3
    + my <<<<  args -Command -
    + CategoryInfo          : ObjectNotFound: (my:String) [], CommandNotFoundE 
   xception
    + FullyQualifiedErrorId : CommandNotFoundException

我打算在不进行任何解析的情况下放入任意参数列表。

编辑:

随着我进一步调查,即使明确指定了命令,我似乎还是做错了什么:

(local bash) $ echo '\n' | ssh -i master-key Admin@10.8.55.78 '$SYSTEMROOT/System32/WindowsPowerShell/v1.0/powershell' -Command 'Write-Host $\($args.Count\)' "my" "args"
0 my args

似乎没有传递任何参数,但由于某种原因它们被打印在控制台上。避免使用 ssh 似乎没有任何改变:

(cygwin) $ $SYSTEMROOT/System32/WindowsPowerShell/v1.0/powershell -Command 'Write-Host $($args.Count)' "my" "args"
0 my args

你不能直接这样做,但我认为这是可以做到的,如果你把你的脚本包装在脚本块中并向它传递参数:

echo "& { $(cat script.ps1) } 'my' 'args'" | ssh user@host "powershell -Command"

由于 -Command 参数不能处理多行字符串,有一种方法可以使用 -EncodedCommand 参数的 Base64 编码值来传递它(虽然不是通过标准输入),但它很丑陋:

ssh user@host "powershell -encodedcommand $((echo "& {"; cat script.ps1 ; echo "} 'my' 'args'") |  iconv -f ascii -t utf-16le | base64 -w0 ; echo -e "\n")

这个按预期工作:

script=$(cat <<-'SCRIPT'
{ 
    $a=$Args[0];
    $b=$Args[1];
    # Do not enclose $script into "" to avoid this comment spread till the EOL
    Write-Host "This is 'a': $a";
    Write-Host "This is 'b': $b";
} # <- call as [[[ -c "& { $script } ... " ]]] if you ommit braces '{}' here 
SCRIPT
)
a="THE VALUE OF THE \"a\""
b="B B B B"
powershell -nologo -executionpolicy bypass  -c "& $script '$a' '$b'"

输出:

> This is 'a': THE VALUE OF THE "a"
> This is 'b': B B B B