2

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
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Sheen
  • 3,333
  • 5
  • 26
  • 46

2 Answers2

4

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.

Andy Arismendi
  • 50,577
  • 16
  • 107
  • 124
  • Can you show me how to use ArgumentList in my case? I tried a couple of ways but no success. Thanks. – Sheen Aug 15 '14 at 12:39
0

I am going to show you the way I do it, passing a file with -FilePath and passing the parameters with -ArgumentList

I create a function that is going to contain the code I want to execute.

#remote_functions.ps1
param($command, $param1, $param2, $param3, $param4, $param5)
$ScriptVersion = "1.0"

function Write5Strings($string1, $string2, $string3, $string4, $string5)
{
    Write-Host "String1: $string1"
    Write-Host "String2: $string2"
    Write-Host "String3: $string3"
    Write-Host "String4: $string4"
    Write-Host "String5: $string5"
    throw "ERROR"
}


try
{
    &$command $param1 $param2 $param3 $param4 $param5
}
catch [System.Exception]
{
    Write-Error $_.Exception.ToString()
    exit 1
} 

And I invoke it this way:

$server="server"
$remotingPort=81

$job = Invoke-Command -AsJob -Port $remotingPort -ComputerName $server -FilePath ".\remote_functions.ps1" -ArgumentList @("Write5Strings", "apple", "banana", "orange", "pear", "watermelon")

Check also this question: How do I pass named parameters with Invoke-Command?

Community
  • 1
  • 1
Oscar Foley
  • 6,817
  • 8
  • 57
  • 90