我正在尝试编写一个简单的包装器,它接受一个输出参数。 这就是现在的样子
function Get-data{
param (
[switch]$network,
[switch]$profile,
[switch]$server,
[switch]$devicebay
)
if ($network.IsPresent) { $item = "network"}
elseif ($profile.IsPresent) {$item = "profile"}
elseif ($server.IsPresent) {$item = "server"}
elseif ($devicebay.IsPresent){$item = "devicebay"}
$command = "show $item -output=script2"
}
显然这可以优化,但我正在努力思考如何实现它。是否有一些简单的方法可以确保只接受和使用单个参数而不诉诸多个 elseif 语句?
另外,我想提供参数数组,而不是按照目前的方式进行。
最佳答案
您可以做的另一件事是使用[ValidateSet]
来代替所有这些开关参数。
function Get-Data{
[cmdletbinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateSet('Network','Profile','Server','DeviceBay')]
[string]$Item
)
Switch ($Item){
'network' {'Do network stuff'}
'profile' {'Do profile stuff'}
'server' {'Do server stuff'}
'devicebay' {'Do devicebay stuff'}
}
}
关于powershell - 多个powershell开关参数——可以优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21528126/