How to force a Powershell Script to run a specific Version

Viewed 2964

I have both Powershell 5.1 and Powershell 7.0 on my computer and I'm try to run a script that has to be run in Powershell 7.0. How do I make the script run in a specific version.

2 Answers

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

Related