Invoke-Command doesn't accept -Path as variable

I am trying to execute a simple Test-Path request to a remote machine using Invoke-Command, but I am struggling with a strange error.

It works:

Invoke-Command -ComputerName COMPUTER001 -ScriptBlock {Test-Path -Path "c:\windows\system.ini"}

      

It fails: "The argument cannot be bound to the Path parameter because it is zero.":

$p_FileName = "c:\windows\system.ini"
Invoke-Command -ComputerName COMPUTER001 -ScriptBlock {Test-Path -Path $p_FileName}

      

I tried using both $ p_FileName and $ ($ p_FileName) but no luck. I'm sure this is something simple, but I'm puzzled.

Any suggestions and hopefully an explanation of what's going on?

Thanks, Andy

+3


source to share


3 answers


You must pass the local variables used in the script block via the -ArgumentList parameter:



$p_FileName = "c:\windows\system.ini"
Invoke-Command -ComputerName COMPUTER001 -ScriptBlock {Test-Path -Path $args[0]} -ArgumentList $p_FileName

      

+4


source


You have a volume problem. The scope in a script block that is running on a remote server cannot access your local variables. There are several ways to get around this. My favorite is $ Using: scope, but many people are unaware of this.

$p_FileName = "c:\windows\system.ini"
Invoke-Command -ComputerName COMPUTER001 -ScriptBlock {Test-Path -Path $Using:p_FileName}

      



For the invoke command, this allows local variables to be used in the script block. This was introduced for use in workflows and can also be used in DSC script blocks.

+2


source


Alternatives to @kevmar and @mjolinor (at least for PS4):

$p_FileName = "c:\windows\system.ini"
$sb = [scriptblock]::create("Test-Path $p_FileName")
Invoke-Command -ComputerName COMPUTER001 -ScriptBlock $sb

      

$ p_FileName resolves on local machine, so COMPUTER001 gets

Test-Path c:\windows\system.ini

      

0


source







All Articles