简体   繁体   中英

Powershell 2.0: Getting different results when running a remote session from a script vs typing it in manually. What's the difference?

I'm getting different results when running a remote session from a script vs typing the exact command sequence in manually. This is happening with a fairly complicated script I'm working on, but I created a tiny little script to demonstrate the issue. Shouldn't the numbers returned be 7-5-7, not 7-5-5?

The script in question

$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

When I run the script, I get this output:

outside remote session
7

inside remote session
5

outside remote session
5

But, when I type in the commands manually, I get this:

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

Why do I get different results?

Enter-PSSession and Exit-PSSession are meant for interactive use. Try this in your script and see what you get:

$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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM