假设您在 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/