1

从脚本运行远程会话与手动键入确切的命令序列时,我得到了不同的结果。这发生在我正在处理的一个相当复杂的脚本中,但我创建了一个很小的脚本来演示这个问题。返回的数字不应该是 7-5-7,而不是 7-5-5?

有问题的脚本

$oldMachineName = "ppal12084229"
$remoteSession = New-PSSession $oldMachineName

$xyz =7

"outside remote session"
$xyz
""

enter-PSSession $remoteSession
$xyz = 5

"inside remote session"
$xyz
""

exit-pssession

"outside remote session"
$xyz
""

remove-pssession $remoteSession

当我运行脚本时,我得到这个输出:

outside remote session
7

inside remote session
5

outside remote session
5

但是,当我手动输入命令时,我得到了这个:

PS H:\> $oldMachineName = "ppal12084229"
PS H:\> $remoteSession = New-PSSession $oldMachineName
PS H:\> $xyz =7
PS H:\> $xyz
7
PS H:\> enter-PSSession $remoteSession
[ppal12084229]: PS C:\WINDOWS\system32> $xyz = 5
[ppal12084229]: PS C:\WINDOWS\system32> $xyz
5
[ppal12084229]: PS C:\WINDOWS\system32> exit-pssession
PS H:\> $xyz
7
PS H:\> remove-pssession $remoteSession

为什么我会得到不同的结果?

4

1 回答 1

2

Enter-PSSessionExit-PSSession用于交互使用。在你的脚本中试试这个,看看你会得到什么:

$oldMachineName = "ppal12084229"
$remoteSession = New-PSSession $oldMachineName

$xyz =7

"outside remote session"
$xyz
""

invoke-command -Session $remoteSession -ScriptBlock {
     $xyz = 5

     "inside remote session"
     $xyz
     ""
}

"outside remote session"
$xyz
""

remove-pssession $remoteSession
于 2012-11-19T17:20:11.633 回答