Reputation: 61
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)?
Upvotes: 6
Views: 15323
Reputation: 180
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
Upvotes: 8
Reputation: 693
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.
Upvotes: 5