如何检查电源外壳中的参数数量?


param (
[string]$Name =  $args[0],#First argument will be the adapter name
[IPAddress]$IP = $args[1],#Second argument will be the IP address
[string]$InterfaceId = $args[3],#Second argument will be the IP address
[string]$VlanId = $args[4], #Fourth argument will be vlanid
[string]$SubnetIP = $args[5],#subnet mask
[string]$IPType = "IPv4",
[string]$Type = "Static"
)
Write-Host $Args.Count

我想检查是否向 powershell 脚本提供了命令行参数,如果未提供,那么我想通过写入显示用法。我正在管理模式下运行脚本。搜索后我找到了一种方法,使用 $Args.Count 我们可以在运行脚本时获取参数计数,但对我来说它总是零。我做错了什么? 在此处输入图像描述

去掉$args[x]作业,在上面添加[cmdletbinding()]

[CmdLetbinding()]
param (
[string]$Name, #First argument will be the adapter name
[IPAddress]$IP, # etc...
[string]$InterfaceId,
[string]$VlanId,
[string]$SubnetIP,
[string]$IPType = "IPv4",
[string]$Type = "Static"
)

然后,可以使用$PSBoundParameters.Count获取参数计数。

$args是一个特殊变量,在命名参数不存在时使用。 因此,由于您有命名参数,它将始终为您提供零计数(除非您添加的参数多于命名参数(

如果使用param块,则无需分配$args[0]和其他块。事实上,这是完全没用的,因为它们会被$null.

另一种方法是,尽管我建议您保留param块,但根本不使用任何命名参数。在这种情况下,$args将按预期工作。

[string]$Name =  $args[0]
[IPAddress]$IP = $args[1]
[string]$InterfaceId = $args[3]
[string]$VlanId = $args[4] 
[string]$SubnetIP = $args[5]
[string]$IPType = "IPv4"
[string]$Type = "Static"

主要区别在于,如果您有param块,则可以通过以下方式调用脚本:

  1. .\MyScript.ps1 -名称 "Hello" -IP 127.0.0.1
  2. .\MyScript.ps1 "Hello" 127.0.0.1

如果没有param块,则只有选项 #2 可用于调用脚本。

最新更新