powershell - 有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容?

标签 powershell powershell-2.0 powershell-3.0

假设您在 Powershell 4.0 环境中编写脚本,并且您想确保脚本在 Powershell 3.0 中工作。您如何确保其向后兼容?

最佳答案

好的,措辞的问题对您要查找的内容更具体一些。听起来你是在问 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.0 的系统上运行。如果这很重要,它也会识别次要构建。

我最近根据自己的需要遇到了这个要求,现在意识到我上面的建议不会让你得到我认为你正在寻找的确切结果。相反,您应该做的是在运行脚本时调用新的 PowerShell session 并使用 -Version启动指定版本的 Windows PowerShell ( TechNet ) 的开关。

所以当你测试你的脚本时,像这样运行它:
powershell -Version 2 -File myscript.ps1

关于powershell - 有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312932/

相关文章:

c# - 使用刷新 token 和 native 应用程序客户端 ID 获取访问 token

powershell - 什么安全设置阻止远程 PowerShell 2.0 访问 UNC 路径

PowerShell 远程处理给出 "Access is Denied"错误

Json 编码 HTML 字符串

powershell - 将参数传递给 PowerShell 作业

windows - 无法通过命令提示符运行 powershell 命令

powershell - Powershell脚本无法在ISE上运行

powershell - 在 PowerShell 模块中忽略 Write-Verbose

.net - 为什么PS抓不到: "New-PSDrive : Logon failure: unknown user (...)"?

.net - PowerShell 3 : Every Command Execution Results In "The type initializer [...] threw an exception" Error