运行 .ps1脚本时通过参数调用多个函数

Calling multiple functions via parameters when running .ps1 script

我有一个 .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' 语句和 'or' 条件,我只是看着用户输入一个函数作为参数。

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

我的快速方法如下。我为每个函数定义一个开关参数,为 "all" 定义一个开关参数,因为我假设不需要顺序。

[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