【问题标题】:Calling multiple functions via parameters when running .ps1 script运行.ps1脚本时通过参数调用多个函数
【发布时间】:2019-07-03 23:08:31
【问题描述】:

我有一个 .ps1 脚本,其中包含多个功能。我希望用户能够放入他们想要运行的功能,而不是一次运行它们。例如。: ./script.ps1 -func1 -func2 或者 ./script.ps1 -全部

我可以通过将用户输入的参数与函数名称进行比较来使其工作,但问题是我希望用户能够以任何顺序放置它。

这是我现在的工作,但我不确定是否可以通过某种方式对其进行优化。

[CmdletBinding()]
Param(
      [Parameter(Mandatory=$false)][String]$Param1,
      [Parameter(Mandatory=$false)][String]$Param2
    )
function Test
{
Write-Host "Test Success"
}
function All
{
Write-Host "All Success"
}
If ($Param1 -eq "Test" -or $Param2 -eq "Test")
{
Test
}
If ($Param1 -eq "All" -or $Param2 -eq "All")
{
All
}

我不只是有一堆带有“或”条件的“if”语句,而是观察用户输入一个函数作为参数。

我确信有一种方法可以使用开关或数组来实现,但我不是一个出色的程序员。

【问题讨论】:

    标签: powershell powershell-2.0 powershell-3.0 powershell-4.0


    【解决方案1】:

    我的快速方法如下。我为每个函数定义了一个开关参数,并为“全部”定义了一个参数,因为我假设不需要该顺序。

    [CmdletBinding()]
    Param(
          [Parameter(Mandatory=$false)][switch]$Func1=$false,
          [Parameter(Mandatory=$false)][switch]$Func2=$false,
          [Parameter(Mandatory=$false)][switch]$All=$false
        )
    
    function Func1 {
        Write-Host "Func1 called"
    }
    
    function Func2 {
        Write-Host "Func2 called"
    }
    
    function All {
        Write-Host "All called"
    }
    
    If ($Func1) {
        Func1
    }
    
    If ($Func2) {
        Func2
    }
    
    If ($All) {
        All
    }
    

    调用脚本,然后运行

    ./script.ps1 -Func2
    

    ./script.ps1 -Func1 -Func2
    

    ./script.ps1 -All
    

    【讨论】:

    • 太棒了,谢谢!我很接近,但我不知道你可以设置 $func=$false,现在这很有意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多