Invoke-Command不一致

时间:2015-03-30 10:26:31

标签: powershell

我有一个尝试在远程服务器上运行某些命令的脚本。有人可以解释为什么我需要在括号中包装我的脚本块的第一行吗?例如:

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential -Credential:$username
$starter = New-PSSession -ComputerName VmProd01.ares.priv -Credential:$cred -Authentication CredSSP
Invoke-Command -Session $starter -ScriptBlock {
    echo 'Output 1'
    echo 'Output 2'
    echo 'Output 3'
    echo 'Output 4'
}
Remove-PSSession $starter

输出"输出1"并在此输出所有内容时停止

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential -Credential:$username
$starter = New-PSSession -ComputerName VmProd01.ares.priv -Credential:$cred -Authentication CredSSP
Invoke-Command -Session $starter -ScriptBlock {
    (echo 'Output 1')
    echo 'Output 2'
    echo 'Output 3'
    echo 'Output 4'
}
Remove-PSSession $starter

我的客户是:

PSVersion                      5.0.9883.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.34209
BuildVersion                   6.4.9883.0
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.2 

远程服务器是:

PSRemotingProtocolVersion      2.1
BuildVersion                   6.1.7601.17514
PSCompatibleVersions           {1.0, 2.0}
PSVersion                      2.0
CLRVersion                     2.0.50727.5485
WSManStackVersion              2.0
SerializationVersion           1.1.0.1

我还应该补充一点,当我添加echo $ PSVersionTable作为我的远程脚本块的第一行来获取这里的版本时,我也得到了所有四个输出。我是否偶然发现了旧版PowerShell中的错误,或者我是否需要在PowerShell中应用其他规则?

1 个答案:

答案 0 :(得分:2)

PowerShell在解析多行格式时非常聪明,但这次看起来似乎失败了。尝试在;语句后添加echo

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential -Credential:$username
$starter = New-PSSession -ComputerName VmProd01.ares.priv -Credential:$cred -Authentication CredSSP
Invoke-Command -Session $starter -ScriptBlock {
    echo 'Output 1';
    echo 'Output 2';
    echo 'Output 3';
    echo 'Output 4';
}

Remove-PSSession $starter

更新:尝试更多变通办法:

$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential -Credential:$username
$starter = New-PSSession -ComputerName VmProd01.ares.priv -Credential:$cred -Authentication CredSSP
Invoke-Command -Session $starter -ScriptBlock {Write-Host 'Output 1'; Write-Host 'Output 2'; Write-Host 'Output 3'; Write-Host 'Output 4';
}

Remove-PSSession $starter
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential -Credential:$username
$starter = New-PSSession -ComputerName VmProd01.ares.priv -Credential:$cred -Authentication CredSSP
Invoke-Command -Session $starter -ScriptBlock {
    $(Write-Host 'Output 1';
    Write-Host 'Output 2';
    Write-Host 'Output 3';
    Write-Host 'Output 4';)
}