powershell - 多个powershell开关参数——可以优化吗?

标签 powershell parameters switch-statement

我正在尝试编写一个简单的包装器,它接受一个输出参数。 这就是现在的样子

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/

相关文章:

c# - 在 C# 中的窗体之间来回传递参数

c - 如何删除主要功能的负责人?

powershell - 为什么总是提示我确认?

sql - 将选择结果作为存储过程的参数传递

java - 如何在java中的while循环中设置switch语句

java - 具有多个语句的 Switch 规则

C - 使用 while 和 switch/case 的菜单程序返回具有无效选择的重复菜单

Powershell 外文件 : Force encoding to Ascii

powershell 不能在反向引用匹配上使用方法

Powershell 将字符串中的双引号替换为单引号