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
source to share
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.
source to share
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
source to share