如何强制运行一个特定版本的Powershell脚本。

5

我在电脑上同时安装了Powershell 5.1和Powershell 7.0,现在我想要运行一个必须在Powershell 7.0中运行的脚本。我该如何让脚本在特定版本中运行?


不是直接回答,但也可以帮助。Requires 指令 可以防止在较低版本的 PowerShell 中运行脚本。 - AKd
2个回答

5

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

如果脚本是通过任务计划程序启动的,则可以在“操作-> 启动程序”部分中使用.exe文件的完整路径,因为它们具有单独的安装位置。
示例图片:Schedule task

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接