Problems using local variables in a remote commands
The remote session can't read your local variables, so you need to send them with your command. There's a few options here. In PowerShell 2.0 you could:
1.Pass them along with -ArgumentList
and use $arg[i]
$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($args[0],$args[1],0)} -ArgumentList $sharepath, $sharename
2.Pass them along with -ArgumentList
and use param()
in your scriptblock to define the arguments
$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { param($sharepath, $sharename) $a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)} -ArgumentList $sharepath, $sharename
In PowerShell 3.0, the using
-variable scope was introduced to make it easier:
$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { $a = [WMICLASS]"Win32_Share"; $a.Create($using:sharepath,$using:sharename,0)}
You could read more about this on about_Remote_Variables @ TechNet