有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容性?
Is there way to know cmdlet version in Powershell for backward compatibility?
假设您正在 Powershell 4.0 环境中编写脚本,并且您希望确保该脚本在 Powershell 3.0 中运行。您如何确保其向后兼容?
这里是获取 "Get-ChildItem" 版本的示例:
(Get-Command Get-ChildItem).Version
好的,问题的措辞更加具体,符合您的要求。听起来你在问 requires.
The#Requires
statement prevents a script from running unless the Windows
PowerShell version, modules, snap-ins, and module and snap-in version
prerequisites are met. If the prerequisites are not met, Windows PowerShell
does not run the script.
这样,在编写脚本时,您可以强制执行脚本的功能版本。
#Requires -Version 3.0
因此,现在当您构建和调试脚本时,您知道它可以在至少 3.0 的系统上运行。如果重要的话,它也能识别次要构建。
我最近出于自己的需要遇到了这个要求,现在我意识到我上面的建议不会让你得到我认为你正在寻找的确切结果。你应该做的是当你 运行 你的脚本调用一个新的 PowerShell 会话并使用 -Version
开关 启动指定版本的 Windows PowerShell(TechNet).
所以当你测试你的脚本时运行它是这样的:
powershell -Version 2 -File myscript.ps1
使用所需命令的 get-module,您可以这样做:
(Get-Module (Get-Command Get-NetTCPConnection).Source).PowerShellVersion
澄清一下:
(Get-command <your cmdlet>). Source
给你安装位置
假设您正在 Powershell 4.0 环境中编写脚本,并且您希望确保该脚本在 Powershell 3.0 中运行。您如何确保其向后兼容?
这里是获取 "Get-ChildItem" 版本的示例:
(Get-Command Get-ChildItem).Version
好的,问题的措辞更加具体,符合您的要求。听起来你在问 requires.
The
#Requires
statement prevents a script from running unless the Windows PowerShell version, modules, snap-ins, and module and snap-in version prerequisites are met. If the prerequisites are not met, Windows PowerShell does not run the script.
这样,在编写脚本时,您可以强制执行脚本的功能版本。
#Requires -Version 3.0
因此,现在当您构建和调试脚本时,您知道它可以在至少 3.0 的系统上运行。如果重要的话,它也能识别次要构建。
我最近出于自己的需要遇到了这个要求,现在我意识到我上面的建议不会让你得到我认为你正在寻找的确切结果。你应该做的是当你 运行 你的脚本调用一个新的 PowerShell 会话并使用 -Version
开关 启动指定版本的 Windows PowerShell(TechNet).
所以当你测试你的脚本时运行它是这样的:
powershell -Version 2 -File myscript.ps1
使用所需命令的 get-module,您可以这样做:
(Get-Module (Get-Command Get-NetTCPConnection).Source).PowerShellVersion
澄清一下:
(Get-command <your cmdlet>). Source
给你安装位置