How to pass string variable to invoke-expression?

Sheen picture Sheen · Aug 15, 2014 · Viewed 9.4k times · Source

I am running the below powershell command:

$cmd = "xxx.exe"

Invoke-Command -ComputerName localhost {Invoke-Expression $cmd}

However I get the error:

Cannot bind argument to parameter 'Command' because it is null.

+ CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterB
indingValidationException
 + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.PowerShell.Commands.InvokeExpressionCommand

Answer

Andy Arismendi picture Andy Arismendi · Aug 15, 2014

Look at the documentation for Invoke-Command.

Use either the -ArgumentList parameter or if powershell 3 see example 9 ($Using:).

http://technet.microsoft.com/en-us/library/hh849719.aspx

ArgumentList Example -

$cmd = "xxx.exe"
Invoke-Command -ComputerName localhost {Invoke-Expression $args[0]} -ArgumentList $cmd

If you use param in the script block you can used named arguments rather than the $args built-in.