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

cgfeq70w  于 12个月前  发布在  Shell
关注(0)|答案(2)|浏览(108)

我在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 [email protected] '$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

rseugnpd

rseugnpd1#

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

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")

snz8szmq

snz8szmq2#

这一个工作如预期:

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

相关问题