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

时间:2019-07-03 14:53:29

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

我有一个.ps1脚本,其中包含多个功能。我希望用户不希望立即运行所有功能,而是希望立即运行它们。例如。: ./script.ps1 -func1 -func2 要么 ./script.ps1-全部

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

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

::Server::Physical.merge( -> { joins(:virtuals)})

我不仅仅是看着一堆带有'or'条件的'if'语句,而是看着用户输入一个函数作为参数。

我敢肯定有一种使用开关或数组的方法,但是我不是一个优秀的程序员。

1 个答案:

答案 0 :(得分:0)

以下是我的快速方法。我为每个功能定义了一个开关参数,为“所有”定义了一个开关参数,因为我假设不需要该顺序。

[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