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

时间:2015-07-03 00:42:09

标签: powershell powershell-v2.0

我想在v2模式下运行powershell脚本。没有包装脚本可以做到这一点吗?

例如,如果我可以使用两个文件,我现在可以这样做。

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版

1 个答案:

答案 0 :(得分:3)

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