How to get path to the correct PowerShell executable? – Powershell

by
Ali Hasan
.net-4.6 azure-powershell c#

Quick Fix: To locate the PowerShell executable, it’s recommended to first check the Path environment variable for pwsh.exe. If it’s not found, fall back to powershell.exe which resides in %SystemRoot%\System32\WindowsPowerShell\v1.0.

The Solutions:

Solution 1: Windows PowerShell and PowerShell (Core)

  • Windows PowerShell: Legacy PowerShell edition that comes with Windows and has the executable name "powershell.exe." Its location is always at %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe.
  • PowerShell (Core): Modern, cross-platform PowerShell edition with the executable name "pwsh.exe" on Windows and "pwsh" on Unix-like platforms. It allows multiple versions to be installed simultaneously.

Finding the Correct Executable:

To determine the correct PowerShell executable on Windows:

  1. Search for "pwsh.exe" in the environment variable "Path". If found, use it as the preferred version.
  2. If "pwsh.exe" is not found, fallback to the legacy "powershell.exe" executable located at %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe.

Caveats:

  • Ensure that any PowerShell code is cross-edition compatible if targeting Windows PowerShell as a fallback.
  • Be aware of feature availability across different versions, even within PowerShell (Core).

Q&A

Is there cross-platform a way on .NET to get path to the latest (or preferably, user-preferred) PowerShell executable without resorting to try to find pwsh.exe in the PATH?

best approach is to look for pwsh.exe via the Path environment variable: that is, consider the pwsh.exe executable, if any, found in the first directory listed in the Path environment variable to be the current user’s preferred version.

Where is PowerShell (Core) executable located?

PowerShell (Core) executable name differs from that of Window PowerShell: it is pwsh.exe (on Windows) / pwsh (on Unix-like platforms).

Is Windows PowerShell still actively maintained?

Windows PowerShell is the legacy, ships-with-Windows, Windows-only PowerShell edition whose latest and last version is 5.1 and which will receive critical security fixes only.

Video Explanation:

The following video, titled "How to make the ultimate Terminal Prompt on Windows 11 - This ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

If I had more time I would have made it shorter. This is taking a Windows 11 machine basically from scratch and getting a perfect PowerShell ...