【问题标题】:how to pass command line parameters to invoked session in powershell 2.0如何在powershell 2.0中将命令行参数传递给调用的会话
【发布时间】:2017-06-26 23:47:32
【问题描述】:

如何将命令行参数传递给在 powershell 2.0 中使用“invoke-command”调用的会话

我的脚本:

param(
    [string]$hostname = 'my_server_name'
)

function createSession($hostname){
    return New-PSSession -ComputerName $hostname -Credential $env:UserDomain\$env:UserName
}
$session = createSession $hostname
invoke-command -Session $session -ScriptBlock {
   write-host $hostname
   write-host $using:hostname
   write-host $script:hostname 
   write-host '**test text**'

}
    Exit-PSSession

输出:(如果我直接打印参数值,我会得到空字符串。)

**test text**

【问题讨论】:

  • -ScriptBlock {} -ArgumentList $hostname
  • 另外,您可以从父会话中引用变量:$using:hostname。我很确定这是 PSv2 友好的。
  • 我试过 -ArgumentList 和 $using 选项。但他们都没有工作。

标签: powershell powershell-2.0 invoke-command


【解决方案1】:

使用参数块

$hostname = $env:computername
Invoke-Command -ScriptBlock { param($hostname)
    Write-OutPut $hostname
} -ArgumentList $hostname

【讨论】:

    【解决方案2】:
    param(
        [string]$hostname = 'my_server_name'
    )
    
    function createSession($hostname){
        return New-PSSession -ComputerName $hostname -Credential $env:UserDomain\$env:UserName
    }
    $session = createSession $hostname
    invoke-command -Session $session -ScriptBlock {
    $hostname=$using:hostname
    
    or
    
    $hostname=$script:hostname
       write-host $hostname
       write-host '**test text**'
    
    }
        Exit-PSSession
    

    希望以上任何一项有所帮助,如果没有请查看powershell中作用域变量的概念,可能会有所帮助 Powershell variable scoping

    【讨论】:

      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2010-11-20
      • 1970-01-01
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多