Restricting Powershell Commands by Version

时间:2016-08-31 17:56:24

标签: powershell

I'm writing a Powershell script (on a Win10 machine) that needs to be backward-compatible all the way to Win7 machines - which shipped with Powershell Version 2.0. I'd like to restrict my command set in the ISE to only those commands available in 2.0, or throw an error if I stray outside that version or something while I'm writing the script - is there an easy way to do this?

3 个答案:

答案 0 :(得分:3)

I don't know if there's a way in the ISE (I think not), but you can start the prompt (console host) separately in 2.0 mode:

powershell.exe -Version 2.0

You could use this in conjunction with ISE by editing and saving the script in ISE, then executing it in the console host. Not ideal, but not too bad of a workaround.

答案 1 :(得分:1)

Set-StrictMode -Version 2.0

MSDN Link

-版本2.0

  • 防止使用尚未初始化的变量(请考虑 VBScript中的选项显式)
  • 无法在上调用不存在的属性 对象
  • 例如,不允许调用类似方法的函数, 做某事(1 2)
  • 禁止创建没有名称的变量

注意,您可以使用它来限制特定方法的某些功能。

关于命令行开关。这里没有任何解决方案。

我建议您使用Get-Help检查每个Commandlet。在那里您可以获得说明的版本。

示例:

Get-Help -Name "Invoke-RestMethod"

答案: ... Windows PowerShell 3.0中引入了此cmdlet。 ...

答案 2 :(得分:-1)

您还可以在脚本本身的顶部包含requires指令。

#requires -version 5

为脚本所需的版本使用正确的数字,2,3,4等。这将确保它在ISE中有效。