有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容? [英] Is there way to know cmdlet version in Powershell for backward compatibility?

查看:53
本文介绍了有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say you are scripting in Powershell 4.0 environment and you want to make sure the script works in Powershell 3.0. How do you ensure its backward compatible?.

推荐答案

好的,措辞上的问题对您要查找的内容更具体一些.听起来您是在要求 requires.

Ok the question as phrased is a little more specific into what you are looking for. Sounds like you are asking for requires.

#Requires 语句阻止脚本运行,除非 WindowsPowerShell 版本、模块、管理单元以及模块和管理单元版本满足先决条件.如果不满足先决条件,Windows PowerShell不运行脚本.

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.

这样,在编写脚本时,您可以强制执行脚本的功能版本.

That way, while you are scripting, you can enforce the functional version of your script.

#Requires -Version 3.0

所以现在当你构建和调试你的脚本时,你知道它可以在至少 3.0.0 的系统上运行.如果重要的话,它也会识别次要构建.

So now while you are building and debugging your script you know that it will work on systems with at least 3.0. It recognizes minor builds as well if that matters.

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

I recently came across this requirement for my own needs and realize now that what I suggested up above will not get you the exact results I think you are looking for. What you should do instead is when you run your script call a new PowerShell session and use the -Version switch which Starts the specified version of Windows PowerShell(TechNet).

所以当你测试你的脚本时,像这样运行它:

So when you are testing your script run it like this:

powershell -Version 2 -File myscript.ps1

这篇关于有没有办法知道 Powershell 中的 cmdlet 版本以实现向后兼容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆