@@ -93,6 +93,27 @@ $DefaultConfigurationName = 'Microsoft.PowerShell'
9393# Specifies the default name of the computer on which to create the compatibility session
9494$DefaultComputerName = ' localhost'
9595
96+ # Location Changed handler that keeps the compatibility session PWD in sync with the parent PWD
97+ # This only applies on localhost.
98+ $locationChangedHandler = {
99+ [PSSession ] $session = Initialize-WinSession @PSBoundParameters - PassThru
100+ if ($session.ComputerName -eq " localhost" )
101+ {
102+ $newPath = $_.newPath
103+ Invoke-Command - Session $session { Set-Location $using :newPath }
104+ }
105+ }
106+
107+ $ExecutionContext.InvokeCommand.LocationChangedAction = $locationChangedHandler
108+
109+ # Remove the location changed handler if the module is removed.
110+ $MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
111+ if ($ExecutionContext.InvokeCommand.LocationChangedAction -eq $locationChangedHandler )
112+ {
113+ $ExecutionContext.InvokeCommand.LocationChangedAction = $null
114+ }
115+ }
116+
96117function Initialize-WinSession
97118{
98119 [CmdletBinding ()]
@@ -143,13 +164,24 @@ function Initialize-WinSession
143164 }
144165 Write-Verbose - Verbose:$verboseFlag " The compatibility session name is '$script :SessionName '."
145166
146- # BUGBUG - need to deal with the possibilities of multiple sessions
147167 $session = Get-PSSession | Where-Object {
148168 $_.ComputerName -eq $ComputerName -and
149169 $_.ConfigurationName -eq $ConfigurationName -and
150170 $_.Name -eq $script :SessionName
151171 }
152172
173+ # Deal with the possibilities of multiple sessions. This might arise
174+ # from the user hitting ctrl-C. We'll make the assumption that the
175+ # first one returned is the correct one and we'll remove the rest.
176+ $session , $rest = $session
177+ if ($rest )
178+ {
179+ foreach ($s in $rest )
180+ {
181+ Remove-PSSession $s
182+ }
183+ }
184+
153185 if ($session -and $session.State -ne " Opened" )
154186 {
155187 Write-Verbose - Verbose:$verboseFlag " Removing closed compatibility session."
@@ -175,8 +207,11 @@ function Initialize-WinSession
175207 $newPSSessionParameters.EnableNetworkAccess = $true
176208 }
177209 Write-Verbose - Verbose:$verboseFlag " Creating a new compatibility session."
178- # #BUGBUG need to deal with the case where there might be multiple sessions because someone hit ctrl-C
179210 $session = New-PSSession @newPSSessionParameters
211+ if ($session.ComputerName -eq " localhost" )
212+ {
213+ Invoke-Command $session { Set-Location $using :PWD }
214+ }
180215 }
181216 else
182217 {
0 commit comments