如何在PowerShell 2.0中将命令行参数传递给调用的会话

时间:2017-06-26 23:47:32

标签: powershell powershell-v2.0 invoke-command

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

我的剧本:

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**

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

使用param block

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