Invoke-Command won't accept -Path as a variable

前端 未结 3 1071
无人及你
无人及你 2020-12-12 00:01

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

This w

相关标签:
3条回答
  • 2020-12-12 00:24

    You have to pass local variables used in the script block through the -ArgumentList parameter:

    $p_FileName = "c:\windows\system.ini"
    Invoke-Command -ComputerName COMPUTER001 -ScriptBlock {Test-Path -Path $args[0]} -ArgumentList $p_FileName
    
    0 讨论(0)
  • 2020-12-12 00:28

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

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

    $p_FileName gets resolved on the local machine so COMPUTER001 receives

    Test-Path c:\windows\system.ini
    
    0 讨论(0)
  • 2020-12-12 00:32

    You have a scope issue. The scope within the script block that runs on the remote server cannot access your local variables. There are several ways around this. My favorite is the $Using: scope but a lot of people do not know about it.

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

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

    0 讨论(0)
提交回复
热议问题