Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to write a script that takes in variables and makes a share on a remote system.

This works:

Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create("C:est","test",0)}

But this doesn't:

$sharepath = "C:est"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)}

I need a way to pass those values somehow.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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:est"
$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:est"
$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:est"
$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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...