如何从脚本中更改我在 运行 中的 powershell 版本?

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

我想 运行 我的 powershell 脚本处于 v2 模式。是否可以在没有包装器脚本的情况下执行此操作?

因此,例如,如果我可以创建两个文件,我现在可以执行此操作。

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'

这会起作用,但我希望我不需要第二个包装文件,因为我正在创建一大堆这些 ps1 脚本,并且拥有包装文件将使我需要的脚本。

我希望我能做这样的事情。

MainContent.ps1

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

稍后,我还希望每个脚本在不使用包装文件的情况下也请求一组凭据。

目前可以吗?

需要说明的是,我使用的是 powershell 的第 2 版

如果您的唯一目标是避免创建单独的包装器脚本,您始终可以让脚本自行重新启动。以下脚本将始终使用 PS 版本 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"

或者你可以让它成为有条件的。仅当版本大于 2.0 时,此脚本才会使用版本 2 重新启动。

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"