Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Pass variable into Invoke-Command for remote execution

$
0
0

I am trying to copy a file on a remote computer by executing a script on my local computer.  The -Path and -Destination  need to be variables.

This work:

Invoke-Command -ComputerName $server -ScriptBlock{
   $fromPath = "C:\MyFolder\MyFile.dat"
   $toPath = $fromPath.Replace("MyFolder", "YourFolder")
   Copy-Item -Path $fromPath -Destination $toPath

}

This does not:
$fromPath = "C:\MyFolder\MyFile.dat"
$toPath = $fromPath.Replace("MyFolder", "YourFolder")
Invoke-Command -ComputerName $server -ScriptBlock{
    Copy-Item -Path $fromPath -Destination $toPath
}
The error:  Cannot bind argument to parameter 'Path' because it is null.
is returned.
This makes sense to me, because i guess the variable needs to be assigned inside of the -ScriptBlock?
However, what I need is to be able to assign the variable outside of the script block - i.e., before the "Invoke-Command" is issued, like in the first example.
Is this possible?
Thanks

Viewing all articles
Browse latest Browse all 6937

Trending Articles