I'm trying to retrieve the Filehash of a file, located in remote server using Invoke-Command
. I'm running my scripts on powershell version 4. It works fine, when i give the full path as below:
Invoke-Command -ComputerName winserver -ScriptBlock {
Get-FileHash E:\test\testfile.zip -Algorithm SHA1
}
The above command works. But I need to pass the file name via a variable as below:
Invoke-Command -ComputerName winserver -ScriptBlock {
Get-FileHash E:\test\$dest.zip -Algorithm SHA1
}
I'm new to scripting and powershell. Please, help me with resolving this!
In PowerShell 4 (3+ actually) the easiest way is to use the
Using
scope modifier:For a solution that works with all versions:
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.using:
only works whenInvoke-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.