Search code examples
powershellinvoke-command

How to use variable as an argument for command in "Invoke-Expression"


I'm getting the error

Cannot bind argument to parameter 'Command' because it is null. + CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand + PSComputerName : X

when I try to use

$command = "cmd.exe /c $($currentLocation)/Ping.cmd"
Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {Invoke-Expression -Command: $command }

How do I use a variable like this? I have this as a requirement so I can't use it directly, it needs to be dynamic.


Solution

  • You can either use the -ArgumentList parameter with Invoke-Command or access your variable using $using: like this:

    Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {
        Invoke-Expression -Command: $using:command
    }