powershellpowershell-1.0

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


I am running powershell script over ssh as ssh user@host "powershell -Comand - < script.ps1. It works as expected until I start passing arguments.

When I put it as powershell -Command - my args it fails (as documented) '-' was specified with the -Command parameter; no other arguments to -Command are permitted.

While the other way around powershell my args -Command - it fails with:

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

I intend to put in arbitrary list of parameter without any parsing.

Edit:

As I investigate further, it seems I am doing something wrong even when the command is specified explicitly:

(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

It seems that passes no arguments but they are printed on console for some reason. Avoiding the ssh does not seems to change anything:

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

Solution

  • You can't do that directly, but I think this can be done, if you wrap your script in scriptblock and pass arguments to it:

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

    Since -Command parameter can't handle multiline strings, there is a way to pass it in (though not via standard input) using Base64 encoded value of -EncodedCommand parameter, but it's ugly:

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