How do I pass a local variable to a remote `Invoke-Command`?

笑着哭i 提交于 2019-11-26 00:26:31

问题


I\'m trying to retrieve the hash of a file located on remote server using Invoke-Command. It works fine when I give the full path as below:

Invoke-Command -ComputerName winserver -ScriptBlock { 
    Get-FileHash -Path E:\\test\\testfile.zip -Algorithm SHA1 
}

But I need to pass the file name via a variable as below:

Invoke-Command -ComputerName winserver -ScriptBlock { 
    Get-FileHash -Path \"E:\\test\\$dest.zip\" -Algorithm SHA1 
}

How do I access this variable in the scriptblock of a remote session?


回答1:


In PowerShell 4 (3+ actually) the easiest way is to use the Using scope modifier:

Invoke-Command -ComputerName winserver -ScriptBlock { 
    Get-FileHash E:\test\$Using:dest.zip -Algorithm SHA1 
}

For a solution that works with all versions:

Invoke-Command -ComputerName winserver -ScriptBlock {
    param($myDest)

    Get-FileHash E:\test\$myDest.zip -Algorithm SHA1 
} -ArgumentList $dest



回答2:


To complement briantist's helpful answer:

The script block passed to Invoke-Command is (as intended) executed on the remote machine, using the remote machine's variables by default.

Thus, in order to use a local variable (value), extra steps are needed (to put it differently: inside a script block executed remotely, you cannot just refer to local variables as you normally would, such as with $dest):

  • PS v3+ offers the using: scope modifier for direct use of a local variable inside the script block - see briantist's first command.

    • Note that using: only works when Invoke-Command actually targets a remote machine.
  • The only option that also works in earlier versions is to pass the local variable as a parameter to the script block. - see briantist's second command.

For more information, refer to Get-Help about_Remote_Variables or the docs online.



来源:https://stackoverflow.com/questions/35492437/how-do-i-pass-a-local-variable-to-a-remote-invoke-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!