Diskdrive
Diskdrive

Reputation: 18825

How can I change the version of powershell I'm running in from within the script?

I would like to run my powershell script in v2 mode. Is it possible to do this without having a wrapper script?

So for example, I can do this now if I can two files.

MainContent.ps1

write-output 'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit" 


Wrapper.ps1

powershell -version 2 -file 'MainContent.ps1'

This will work but I'm hoping I don't need to have this second wrapper file because I'm creating a whole bunch of these ps1 scripts, and having wrapper files will double the amount of scripts I'll need.

I'm hoping I can do something like this.

MainContent.ps1

Set-Powershell -version 2
write-output 'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit" 

Later on, I would also like each script to ask for a set of credentials as well without using a wrapper file.

Is this currently possible?

To be clear, I'm using version 2 of powershell

Upvotes: 6

Views: 28383

Answers (1)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

If your only goal is to avoid creating separate wrapper scripts, you can always have the script re-launch itself. The following script will always re-launch itself once with PS version 2.0.

param([switch]$_restart)
if (-not $_restart) {
  powershell -Version 2 -File $MyInvocation.MyCommand.Definition -_restart
  exit
}

'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit"

Or you can make it conditional. This script re-launches itself with version 2 only if the version is greater than 2.0.

if ($PSVersionTable.PSVersion -gt [Version]"2.0") {
  powershell -Version 2 -File $MyInvocation.MyCommand.Definition
  exit
}

'run some code'
Read-Host -Prompt "Scripts Completed : Press any key to exit"

Upvotes: 9

Related Questions