如何将CmdletBinding参数绑定到PowerShell中的for循环

时间:2016-04-29 10:56:40

标签: powershell

我正在尝试让我的CmdletBinding在PowerShell中工作。

[CmdletBinding()]
Param(
[Parameter(Mandatory=$False,ParameterSetName='firewallIndex', Position=0)]
[switch]$fwIndex,

[Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=0)]
[string]$fwName = ( Read-host "Input Firewall Index" ),

[Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=1)]
[string]$fwCommand = ( Read-host "Input Firewall Command")
)

$allFirewallIps = (Get-Content $dir\firewallips.txt) 

当我使用-fwIndex开关运行时,我只希望它执行此操作,这将返回带有索引的防火墙列表

for($i=0; $i-le $allFirewallIps.Length-1; $i++)
         {"`[{0}] = {1}” -f $i,$allFirewallIps[$i]}    

返回:

[0] = 10.1.128.4 fw-ips-labA
[1] = 10.1.128.5 fw-ips-labB
[2] = 10.1.17.128 fw-extranet
[3] = 10.1.17.214 fw-ukdr
[4] = 10.1.17.215 fw-ukvpna
[5] = 10.1.17.216 fw-ukvpnb 

我用这个

尝试了
if ($PSCmdlet.ShouldProcess("$fwIndex"))

但是当我运行命令时,它会遍历所有Cmdlet,我会收到$fwName$fwCommand个参数,要求我输入。

fwcommand_run.ps1 -fwIndex
**Input Firewall Index: 
Input Firewall Command:** 
[0] = 10.1.128.4 fw-ips-labA
[1] = 10.1.128.5 fw-ips-labB
[2] = 10.1.17.128 fw-extranet
[3] = 10.1.17.214 fw-ukdr
[4] = 10.1.17.215 fw-ukvpna
[5] = 10.1.17.216 fw-ukvpnb

如何将for循环绑定到$fwIndex开关?

1 个答案:

答案 0 :(得分:1)

由于$fwName cmdlet,系统会要求您输入$fwCommandRead-Host。只需省略它们:

[CmdletBinding()]
Param(
[Parameter(Mandatory=$False,ParameterSetName='firewallIndex', Position=0)]
[switch]$fwIndex,

[Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=0)]
[string]$fwName,

[Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=1)]
[string]$fwCommand
)

$allFirewallIps = (Get-Content $dir\firewallips.txt) 

您可以在参数中添加HelpMessage

[Parameter(Mandatory=$True, ParameterSetName='firewallCommand',Position=0, HelpMessage="Input Firewall Index")]

如果现在使用 firewallCommand 参数集调用cmdlet,您将得到如下内容:

Supply values for the following parameters:
(Type !? for Help.)
fwName: 

如果您输入!?,您会看到帮助文字。

要检查是否设置了开关,只需使用$fwIndex.IsPresent