Search code examples
powershellbatch-filecmd

.Bat file unable to run powershell 7


I have set up a very simple .bat file to execute a couple of commands to save me typing them out every time, however the processes need to be run in powershell 7.

If i manually run powershell 7.0.3 and then run the commands everything work, however running the .bat script starting

powershell -Version 7.0.3 -Command {XXXXX};

presents me with a message "Cannot start Windows PowerShell version 7.0.3 because it is not installed."

If i try and run it without the version number then it runs in 5.1.x and this then fails as it requires 6+.


Solution

  • tl;dr

    As Lee_Dailey notes, you must use pwsh.exe, not powershell.exe, to start a version of PowerShell [Core] v6+ and you must invoke the desired version's specific executable.

    In the simplest case:

    pwsh -Command "XXXXX"
    

    Note that I've replaced {XXXXX} with "XXXXX", because you cannot directly execute script blocks ({...}) from outside PowerShell - just supply the commands as a string.


    Given that - unlike with Windows PowerShell - you can install multiple PowerShell [Core] versions side by side:

    • Run pwsh -version (sic; see below) to report the version in your system's path (the instance that comes first among the directories listed in the PATH environment variable, $env:PATH).

    • If it is not the one you want to target, you'll have to invoke it via its full path:

      • If you want to rely on the standard installation location, you can use the following on Windows for version 7.0: "C:\Program Files\PowerShell\7\pwsh.exe"

      • To determine the target version's executable location reliably, open an interactive console for it and run (Get-Process -Id $PID).Path


    The -Version parameter of powershell.exe, the Windows PowerShell CLI, does not allow you to start just any PowerShell version, only an older version of Windows PowerShell:

    • In fact, the only supported argument is -Version 2, and even that will only succeed if you have previously installed the required legacy versions of .NET Framework.
    • Caveat: While versions higher than v5.1 - the latest and last Windows PowerShell version - sensibly result in an error (the one you saw), unsupported lower versions are quietly ignored; in effect, -Version 1 and -Version 2 will both start version 2.0, whereas -Version 3, -Version 4 and -Version 5 are effectively ignored and run v5.1 - verify with $PSVersionTable.PSVersion

    While a -Version parameter still exists in pwsh.exe, the PowerShell [Core] v6+ CLI, its meaning has changed: It now simply reports a version number, namely the targeted executable's own (and therefore takes no argument).