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

how to pass command line parameters to invoked session in powershell 2.0

如何将命令行参数传递给在 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**
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

使用参数块

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