如何强制 Powershell 脚本运行特定版本

Nat*_*vis 5 shell powershell powershell-core

我的计算机上同时安装了 PowerShell 5.1 和 PowerShell 7.0。如何为给定脚本(在本例中为 PowerShell 7.0)强制执行 PowerShell 的强制版本(特定版本,而不是最低或最高版本)?

小智 4

如果它是在 PS shell 中调用的脚本,如果版本不正确,您可以重新启动它。

# 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
Run Code Online (Sandbox Code Playgroud)

如果脚本是通过任务计划程序启动的,您只需在“操作 -> 启动程序”部分中使用 .exe 的完整路径,因为它们具有单独的安装位置。

安排任务