0

I have a PowerShell remoting script that the test-path is always false from variable.

$pathname = "C:\temp"
$hostremote = "computer122" #example

example - does not work:

Invoke-Command -ComputerName $hostremote {Test-Path -Path '$pathname' }

example - works fine:

Invoke-Command -ComputerName $hostremote {Test-Path -Path 'C:\temp' }

I tried using " and that causes an error so as leaving the ' or " out. Got to be a simple powershell trick I am missing for such a simple thing.

Zippy
  • 455
  • 1
  • 11
  • 25
  • 2
    Try `Invoke-Command -ComputerName $hostremote {Test-Path -Path $using:pathname }`. `Invoke-Command` runs in a remote scope. Local variables are not available in that scope. And yes, don't use single quotes around variables that you want to expand with exception to those single quotes being surrounded by outer double quotes. – AdminOfThings Jan 04 '22 at 16:37
  • 1
    Use the command `help Invoke-Command -Full` where `Example 9` explains the use of `using:`. – lit Jan 04 '22 at 16:43

1 Answers1

1

Several problems there:

First, never use single quote when calling a variable. If you want to use a variable as is, why using quotes ? -Path $pathnameis far simplier. If you want to set within something else, then use double quotes -Path "$pathname\SomeSubDir"

Second, your variable is in a distinct scope, so you cannot retrieve it like this, so you can do this

Invoke-Command -ComputerName $hostremote {Test-Path -Path $using:pathname }

but this seems awful to me, and I would prefer this :

Invoke-Command -ComputerName $hostremote {Test-Path -Path $args[0] } -ArgumentList $pathname
CFou
  • 978
  • 3
  • 13