Open windows from a previous session does not restore the working directories of any tab #18738

Closed
opened 2026-01-31 06:22:58 +00:00 by claunia · 7 comments
Owner

Originally created by @halim2209 on GitHub (Oct 21, 2022).

Windows Terminal version

1.15.2874.0

Windows build number

10.0.19042.0

Other Software

 pwsh > Get-Module

ModuleType Version    PreRelease Name                                ExportedCommands
---------- -------    ---------- ----                                ----------------
Manifest   7.0.0.0               Microsoft.PowerShell.Management     {Add-Content, Clear-Content, Clear-Item, Clear-ItemProperty…}
Manifest   7.0.0.0               Microsoft.PowerShell.Utility        {Add-Member, Add-Type, Clear-Variable, Compare-Object…}
Script     0.0                   oh-my-posh-core                     {Enable-PoshLineError, Enable-PoshTooltips, Enable-PoshTransientPrompt, Export-PoshTheme…}
Script     1.1.0                 posh-git                            {Add-PoshGitToProfile, Expand-GitCommand, Format-GitBranchName, Get-GitBranchStatusColor…}
Script     2.2.6                 PSReadLine                          {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler…}
Script     0.10.0                Terminal-Icons                      {Add-TerminalIconsColorTheme, Add-TerminalIconsIconTheme, Format-TerminalIcons, Get-TerminalIconsColorThe…

Steps to reproduce

  1. Configure Windows Terminal to "open windows from a previous session"
  2. Open various tabs, switch to different working directories
  3. Close Windows Terminal

Expected Behavior

Windows Terminal to restore the previous session with all tabs having opened their last working directory.

Actual Behavior

Windows Terminal restores the tabs and panes as expected, but does not switch into the correct directories, instead remains in the default configured

Interestingly enough, all other attributes are saved correctly: Window position and size, names of the tabs, and panes including their sizes.

The states.json file only contains "null" as the startingDirectory:

{
	"persistedWindowLayouts" : 
	[
		{
			"initialPosition" : "-1468,116",
			"initialSize" : 
			{
				"height" : 586.0,
				"width" : 1113.0
			},
			"launchMode" : "default",
			"tabLayout" : 
			[
				{
					"action" : "newTab",
					"commandline" : "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\"",
					"profile" : "PowerShell",
					"startingDirectory" : null,
					"suppressApplicationTitle" : false,
					"tabTitle" : "PowerShell"
				},
				{
					"action" : "splitPane",
					"commandline" : "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\"",
					"profile" : "PowerShell",
					"size" : 0.24999994039535522,
					"split" : "down",
					"splitMode" : "manual",
					"startingDirectory" : null,
					"suppressApplicationTitle" : false,
					"tabTitle" : "PowerShell"
				},
				{
					"action" : "renameTab",
					"title" : "test-title"
				},
				{
					"action" : "focusPane",
					"id" : 1
				}
			]
		}
	]
}

The following are the contents of $PROFILE:


Import-Module posh-git
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\thecyberden.omp.json" | Invoke-Expression

Import-Module PSReadLine
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineOption -EditMode Windows

Import-Module -Name Terminal-Icons
Originally created by @halim2209 on GitHub (Oct 21, 2022). ### Windows Terminal version 1.15.2874.0 ### Windows build number 10.0.19042.0 ### Other Software ``` pwsh > Get-Module ModuleType Version PreRelease Name ExportedCommands ---------- ------- ---------- ---- ---------------- Manifest 7.0.0.0 Microsoft.PowerShell.Management {Add-Content, Clear-Content, Clear-Item, Clear-ItemProperty…} Manifest 7.0.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object…} Script 0.0 oh-my-posh-core {Enable-PoshLineError, Enable-PoshTooltips, Enable-PoshTransientPrompt, Export-PoshTheme…} Script 1.1.0 posh-git {Add-PoshGitToProfile, Expand-GitCommand, Format-GitBranchName, Get-GitBranchStatusColor…} Script 2.2.6 PSReadLine {Get-PSReadLineKeyHandler, Get-PSReadLineOption, Remove-PSReadLineKeyHandler, Set-PSReadLineKeyHandler…} Script 0.10.0 Terminal-Icons {Add-TerminalIconsColorTheme, Add-TerminalIconsIconTheme, Format-TerminalIcons, Get-TerminalIconsColorThe… ``` ### Steps to reproduce 1. Configure Windows Terminal to "open windows from a previous session" 2. Open various tabs, switch to different working directories 3. Close Windows Terminal ### Expected Behavior Windows Terminal to restore the previous session with all tabs having opened their last working directory. ### Actual Behavior Windows Terminal restores the tabs and panes as expected, but does not switch into the correct directories, instead remains in the default configured Interestingly enough, all other attributes are saved correctly: Window position and size, names of the tabs, and panes including their sizes. The states.json file only contains "null" as the `startingDirectory`: ``` { "persistedWindowLayouts" : [ { "initialPosition" : "-1468,116", "initialSize" : { "height" : 586.0, "width" : 1113.0 }, "launchMode" : "default", "tabLayout" : [ { "action" : "newTab", "commandline" : "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\"", "profile" : "PowerShell", "startingDirectory" : null, "suppressApplicationTitle" : false, "tabTitle" : "PowerShell" }, { "action" : "splitPane", "commandline" : "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\"", "profile" : "PowerShell", "size" : 0.24999994039535522, "split" : "down", "splitMode" : "manual", "startingDirectory" : null, "suppressApplicationTitle" : false, "tabTitle" : "PowerShell" }, { "action" : "renameTab", "title" : "test-title" }, { "action" : "focusPane", "id" : 1 } ] } ] } ``` The following are the contents of `$PROFILE`: ``` Import-Module posh-git oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH\thecyberden.omp.json" | Invoke-Expression Import-Module PSReadLine Set-PSReadLineOption -PredictionSource History Set-PSReadLineOption -PredictionViewStyle ListView Set-PSReadLineOption -EditMode Windows Import-Module -Name Terminal-Icons ```
claunia added the Issue-QuestionNeeds-TriageResolution-AnsweredNeeds-Attention labels 2026-01-31 06:22:58 +00:00
Author
Owner

@zadjii-msft commented on GitHub (Oct 21, 2022):

Did you configure your shell to tell the Terminal what the CWD is/?

Refer to: Opening a tab or pane in the same directory in Windows Terminal.

See also https://github.com/microsoft/terminal/issues?q=is%3Aissue++restore+directory+

@zadjii-msft commented on GitHub (Oct 21, 2022): Did you configure your shell to tell the Terminal what the CWD is/? Refer to: [Opening a tab or pane in the same directory in Windows Terminal](https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory). See also https://github.com/microsoft/terminal/issues?q=is%3Aissue++restore+directory+
Author
Owner

@halim2209 commented on GitHub (Oct 21, 2022):

That seems to fix the issue with the startingDirectory not being populated but now oh-my-posh does not seem to work any longer.
I have tried both snippets from the first link, the snippet for PowerShell:

function prompt {
  $loc = $($executionContext.SessionState.Path.CurrentLocation);
  $out = "PS $loc$('>' * ($nestedPromptLevel + 1)) ";
  $out += "$([char]27)]9;9;`"$loc`"$([char]27)\"
  return $out
}

As well as the one for posh-git:

function prompt
{
  $loc = Get-Location

  $prompt = & $GitPromptScriptBlock

  $prompt += "$([char]27)]9;12$([char]7)"
  if ($loc.Provider.Name -eq "FileSystem")
  {
    $prompt += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  $prompt
}

Both seem to disable oh-my-posh. Is there a way to get both working?
I couldn't find anything with regards to "oh-my-posh prompt function". It seems these two things are a disturbance to one another...

@halim2209 commented on GitHub (Oct 21, 2022): That seems to fix the issue with the `startingDirectory` not being populated but now `oh-my-posh` does not seem to work any longer. I have tried both snippets from the first link, the snippet for PowerShell: ``` function prompt { $loc = $($executionContext.SessionState.Path.CurrentLocation); $out = "PS $loc$('>' * ($nestedPromptLevel + 1)) "; $out += "$([char]27)]9;9;`"$loc`"$([char]27)\" return $out } ``` As well as the one for `posh-git`: ``` function prompt { $loc = Get-Location $prompt = & $GitPromptScriptBlock $prompt += "$([char]27)]9;12$([char]7)" if ($loc.Provider.Name -eq "FileSystem") { $prompt += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)" } $prompt } ``` Both seem to disable `oh-my-posh`. Is there a way to get both working? I couldn't find anything with regards to "oh-my-posh prompt function". It seems these two things are a disturbance to one another...
Author
Owner

@237dmitry commented on GitHub (Oct 21, 2022):

Both seem to disable oh-my-posh

I think oh-my-posh has its own prompt function. Your prompt replaces it with itself. Add to oh-my-posh's prompt:

"`e]9;9;${PWD}`e\"

if you use Windows Powershell, not PowerShell 7, then `e replace with $([char] 27)

Just try:

PS > get-content function:prompt | Set-Clipboard

Edit and paste it in:

PS > function prompt {
>>  paste here
>>}

PS. This is only for current powershell session. If this work edit oh-my-posh script code.

@237dmitry commented on GitHub (Oct 21, 2022): > Both seem to disable oh-my-posh I think `oh-my-posh` has its own prompt function. Your prompt replaces it with itself. Add to oh-my-posh's prompt: ``` "`e]9;9;${PWD}`e\" ``` if you use Windows Powershell, not PowerShell 7, then \`e replace with `$([char] 27)` Just try: ``` PS > get-content function:prompt | Set-Clipboard ``` Edit and paste it in: ``` PS > function prompt { >> paste here >>} ``` PS. This is only for current powershell session. If this work edit `oh-my-posh` script code.
Author
Owner

@ghost commented on GitHub (Oct 28, 2022):

This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for 4 days. It will be closed if no further activity occurs within 3 days of this comment.

@ghost commented on GitHub (Oct 28, 2022): This issue has been automatically marked as stale because it has been marked as requiring author feedback but has not had any activity for **4 days**. It will be closed if no further activity occurs **within 3 days of this comment**.
Author
Owner

@halim2209 commented on GitHub (Oct 28, 2022):

Unfortunately, I was not able to get it to work.

@237dmitry: When I run PS > get-content function:prompt | Set-Clipboard I get the following copied into the clipboard:

	# store the orignal last command execution status and last exit code
	$script:OriginalLastExecutionStatus = $?
	$script:OriginalLastExitCode = $global:LASTEXITCODE

	Set-PoshPromptType
	if ($script:PromptType -ne 'transient') {
		Update-PoshErrorCode
	}
	$cleanPSWD = Get-CleanPSWD
	$stackCount = global:Get-PoshStackCount
	Set-PoshContext
	$terminalWidth = $Host.UI.RawUI.WindowSize.Width
	# set a sane default when the value can't be retrieved
	if (-not $terminalWidth) {
		$terminalWidth = 0
	}
	$standardOut = @(Start-Utf8Process $script:OMPExecutable @("print", $script:PromptType, "--error=$script:ErrorCode", "--pswd=$cleanPSWD", "--execution-time=$script:ExecutionTime", "--stack-count=$stackCount", "--config=$env:POSH_THEME", "--shell-version=$script:PSVersion", "--terminal-width=$terminalWidth", "--shell=$script:ShellName"))
	# make sure PSReadLine knows if we have a multiline prompt
	Set-PSReadLineOption -ExtraPromptLineCount (($standardOut | Measure-Object -Line).Lines - 1)
	# the output can be multiline, joining these ensures proper rendering by adding line breaks with `n
	$standardOut -join "`n"

	# remove any posh-git status
	$env:POSH_GIT_STATUS = $null

	# restore the orignal last exit code
	$global:LASTEXITCODE = $script:OriginalLastExitCode
	

I tried wrapping this in a function prompt { ... } while also adding the line "`e]9;9;${PWD}`e\" to the end of the prompt function. When I do, my prompt turns into this: PS>
No current working path, no oh-my-posh either. Plus, the state.json is no longer updated with the correct paths.
Am I doing something wrong?

When I installed Windows Terminal and oh-my-posh on my previous laptop two years ago, I didn't have to change the prompt function. Everything worked out of the box.

@halim2209 commented on GitHub (Oct 28, 2022): Unfortunately, I was not able to get it to work. @237dmitry: When I run `PS > get-content function:prompt | Set-Clipboard` I get the following copied into the clipboard: ``` # store the orignal last command execution status and last exit code $script:OriginalLastExecutionStatus = $? $script:OriginalLastExitCode = $global:LASTEXITCODE Set-PoshPromptType if ($script:PromptType -ne 'transient') { Update-PoshErrorCode } $cleanPSWD = Get-CleanPSWD $stackCount = global:Get-PoshStackCount Set-PoshContext $terminalWidth = $Host.UI.RawUI.WindowSize.Width # set a sane default when the value can't be retrieved if (-not $terminalWidth) { $terminalWidth = 0 } $standardOut = @(Start-Utf8Process $script:OMPExecutable @("print", $script:PromptType, "--error=$script:ErrorCode", "--pswd=$cleanPSWD", "--execution-time=$script:ExecutionTime", "--stack-count=$stackCount", "--config=$env:POSH_THEME", "--shell-version=$script:PSVersion", "--terminal-width=$terminalWidth", "--shell=$script:ShellName")) # make sure PSReadLine knows if we have a multiline prompt Set-PSReadLineOption -ExtraPromptLineCount (($standardOut | Measure-Object -Line).Lines - 1) # the output can be multiline, joining these ensures proper rendering by adding line breaks with `n $standardOut -join "`n" # remove any posh-git status $env:POSH_GIT_STATUS = $null # restore the orignal last exit code $global:LASTEXITCODE = $script:OriginalLastExitCode ``` I tried wrapping this in a `function prompt { ... }` while also adding the line ```"`e]9;9;${PWD}`e\"``` to the end of the prompt function. When I do, my prompt turns into this: `PS>` No current working path, no oh-my-posh either. Plus, the state.json is no longer updated with the correct paths. Am I doing something wrong? When I installed Windows Terminal and oh-my-posh on my previous laptop two years ago, I didn't have to change the prompt function. Everything worked out of the box.
Author
Owner

@zadjii-msft commented on GitHub (Oct 28, 2022):

Maybe take a look at https://github.com/JanDeDobbeleer/oh-my-posh/discussions/1532? Admittedly, I'm not familiar with how exactly oh-my-posh works. There's gotta be a way to insert an OSC9;9 somewhere in there

@zadjii-msft commented on GitHub (Oct 28, 2022): Maybe take a look at https://github.com/JanDeDobbeleer/oh-my-posh/discussions/1532? Admittedly, I'm not familiar with how exactly oh-my-posh works. There's gotta be a way to insert an OSC9;9 somewhere in there
Author
Owner

@halim2209 commented on GitHub (Oct 30, 2022):

@zadjii-msft thank you! This fixes the issue.
Issue was in the configuration of oh-my-posh rather than Windows Terminal.

@halim2209 commented on GitHub (Oct 30, 2022): @zadjii-msft thank you! This fixes the issue. Issue was in the configuration of oh-my-posh rather than Windows Terminal.
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/terminal#18738