4

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:\test","test",0)}

But this doesn't:

$sharepath = "C:\test"
$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.

1 Answer 1

6

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 $args[$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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.