Search code examples
powershellinvoke-command

How to pass string variable to invoke-expression?


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

Solution

  • 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.