1

I'm tearing my hair out trying to invoke-command but pass the path to the exe as a parameter

eg: I want to take this command

powershell Invoke-Command -ComputerName localhost -ScriptBlock { param($command ) C:\windows\system32\getmac.exe /$command } -ArgumentList ?

and translate it into a form like this

powershell Invoke-Command -ComputerName localhost -ScriptBlock { param($path, $command ) $path\getmac.exe /$command } -ArgumentList C:\windows\system32,?

I've tried all manner of quoting, ampersands and other contortions but can't get it to work. The above attempt results in

Unexpected token '\getmac.exe' in expression or statement. At line:1 char:97

(I don't really want to invoke getmac on localhost, this is the runnable, SO distilled version)

0

2 Answers 2

7

Try this option. It shows me help for cscript.exe.

C:\>powershell.exe Invoke-Command -ComputerName localhost -ScriptBlock { param($path, $command ) cmd /c $path $command } -args '"C:\windows\system32\cscript.exe"','"/?"'

I tried other options using & and then path and arguments and it was giving me missing } exception. Then using cmd /c instead of & inside scriptblock fixed the issue.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks - this works. Was hoping to not have to use the cmd trick but it is the only working solution I've found.
1

Powershell won't parse a string as a command that way. For e.g. if you do this:

$path="C:\Windows\System32"
$path\getmac.exe

You would get the same error. The trick to work around this is to use the invoke operator &:

&$path\getmac.exe

or in your example, like this (also note that for a command that you pass to the powershell executable, you must wrap it in scriptblock braces):

powershell -command {Invoke-Command -ComputerName localhost -ScriptBlock { param($path, $command ) &$path\getmac.exe /$command } -ArgumentList C:\windows\system32,?}

5 Comments

I tried this tack but adding & to the invoke-command changes the error to 'Missing closing '}' in statement block.' (try running your example with localhost for server).
@fiat just noticed you were executing through powershell executable, try wrapping the whole command in braces.
no joy :( similar missing closing '}' error. Note that without the $path param it works fine without the outer braces.
hmmm. I was running PS2.0, upgraded to PS3.0, same result. OS=Win7, running from command prompt, not PS prompt. tweaked your answer to run against localhost so exact copy paste repro.
@fiat did you check my solution by replacing & with cmd /c and including your parameters in quotes?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.