Problems using local variables in a remote commands

前端 未结 1 1598
独厮守ぢ
独厮守ぢ 2020-12-11 10:50

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 {         


        
相关标签:
1条回答
  • 2020-12-11 11:08

    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

    0 讨论(0)
提交回复
热议问题