@@ -95,6 +95,27 @@ $SessionConfigurationName = 'Microsoft.PowerShell'
9595
9696Set-Alias - Name Add-WinPSModulePath - Value Add-WindowsPSModulePath
9797
98+ # Location Changed handler that keeps the compatibility session PWD in sync with the parent PWD
99+ # This only applies on localhost.
100+ $locationChangedHandler = {
101+ [PSSession ] $session = Initialize-WinSession @PSBoundParameters - PassThru
102+ if ($session.ComputerName -eq " localhost" )
103+ {
104+ $newPath = $_.newPath
105+ Invoke-Command - Session $session { Set-Location $using :newPath }
106+ }
107+ }
108+
109+ $ExecutionContext.InvokeCommand.LocationChangedAction = $locationChangedHandler
110+
111+ # Remove the location changed handler if the module is removed.
112+ $MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
113+ if ($ExecutionContext.InvokeCommand.LocationChangedAction -eq $locationChangedHandler )
114+ {
115+ $ExecutionContext.InvokeCommand.LocationChangedAction = $null
116+ }
117+ }
118+
98119function Initialize-WinSession
99120{
100121 [CmdletBinding ()]
@@ -170,6 +191,18 @@ function Initialize-WinSession
170191 $_.Name -eq $script :SessionName
171192 } | Select-Object - First 1
172193
194+ # Deal with the possibilities of multiple sessions. This might arise
195+ # from the user hitting ctrl-C. We'll make the assumption that the
196+ # first one returned is the correct one and we'll remove the rest.
197+ $session , $rest = $session
198+ if ($rest )
199+ {
200+ foreach ($s in $rest )
201+ {
202+ Remove-PSSession $s
203+ }
204+ }
205+
173206 if ($session -and $session.State -ne " Opened" )
174207 {
175208 Write-Verbose - Verbose:$verboseFlag " Removing closed compatibility session."
@@ -194,8 +227,13 @@ function Initialize-WinSession
194227 {
195228 $newPSSessionParameters.EnableNetworkAccess = $true
196229 }
197- Write-Verbose - Verbose:$verboseFlag " Created new session on host '$computername '"
230+
231+ Write-Verbose - Verbose:$verboseFlag " Created new compatibiilty session on host '$computername '"
198232 $session = New-PSSession @newPSSessionParameters | Select-Object - First 1
233+ if ($session.ComputerName -eq " localhost" )
234+ {
235+ Invoke-Command $session { Set-Location $using :PWD }
236+ }
199237 }
200238 else
201239 {
0 commit comments