diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 1089985ec0f..e6e8759d3cd 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -113,13 +113,17 @@ internal static int Start(string bannerText, string helpText, string[] args) // put PSHOME in front of PATH so that calling `powershell` within `powershell` always starts the same running version string path = Environment.GetEnvironmentVariable("PATH"); - if (path != null) + string pshome = Utils.DefaultPowerShellAppBase + Path.PathSeparator; + + // to not impact startup perf, we don't remove duplicates, but we avoid adding a duplicate to the front + // we also don't handle the edge case where PATH only contains $PSHOME + if (string.IsNullOrEmpty(path)) { - string pshome = Utils.DefaultPowerShellAppBase; - if (!path.Contains(pshome)) - { - Environment.SetEnvironmentVariable("PATH", pshome + Path.PathSeparator + path); - } + Environment.SetEnvironmentVariable("PATH", pshome); + } + else if (!path.StartsWith(pshome)) + { + Environment.SetEnvironmentVariable("PATH", pshome + path); } try diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index e18389fd9be..d09f3bb02e1 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -987,3 +987,25 @@ Describe 'Pwsh startup in directories that contain wild cards' -Tag CI { } } } + +Describe 'Pwsh startup and PATH' -Tag CI { + BeforeEach { + $oldPath = $env:PATH + } + + AfterEach { + $env:PATH = $oldPath + } + + It 'Calling pwsh starts the same version of PowerShell as currently running' { + $version = pwsh -v + $version | Should -BeExactly "PowerShell $($PSVersionTable.GitCommitId)" + } + + It 'pwsh starts even if PATH is not defined' { + $pwsh = Join-Path -Path $PSHOME -ChildPath "pwsh" + Remove-Item Env:\PATH + $path = & $pwsh -noprofile -command '$env:PATH' + $path | Should -BeExactly ($PSHOME + [System.IO.Path]::PathSeparator) + } +}