6

I have both PowerShell 5.1 and PowerShell 7.0 on my computer. How can I enforce a mandatory version (a specific version, not a minimum or maximum version #) of PowerShell for a given script (in this case, PowerShell 7.0)?

1
  • Not a direct answer, but also can help. Requires directive can prevent running the script in a lower PS version. Commented Apr 21, 2022 at 14:04

2 Answers 2

7

another option is to use #Requires statement

#Requires -Version 7.0 

here is the reference from Microsoft support

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_requires

Sign up to request clarification or add additional context in comments.

1 Comment

-1. This will stipulate the minimum version needed to run the script, but it will not force a certain version of PowerShell, as the question requires.
5

If it's a script being invoked in a PS shell, you could relaunch it if it's not the correct version.

# At beginning of .ps1 if ($PSVersionTable.PSVersion -ne [Version]"5.1") { # Re-launch as version 5 if we're not already powershell -Version 5.1 -File $MyInvocation.MyCommand.Definition exit } # Your script code 

If the scripts are launched via Task Scheduler, you could just use the full path to the .exe in the "Actions -> Start a program" section, as they have separate install locations.

Schedule task

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.