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

♀尐吖头ヾ 提交于 2020-05-15 07:45:39

问题


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


回答1:


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"


来源:https://stackoverflow.com/questions/31196825/how-can-i-change-the-version-of-powershell-im-running-in-from-within-the-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!