我有一个.ps1脚本,其中包含多个功能。我希望用户不希望一次运行所有功能,而是希望能够一次运行它们。例如:./script.ps1 -func1 -func2或./script.ps1 -All
我可以通过将用户输入的参数与函数名称进行比较来使其工作,但是问题是我希望用户能够以任意顺序放置它。
这是我现在正在工作的内容,但是我不确定是否可以通过某种方式对其进行优化。
[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”语句,而是看着用户输入一个函数作为参数。
我敢肯定有一种使用开关或阵列的方法,但是我不是一个优秀的程序员。
我的快速方法如下。我为每个功能定义了一个开关参数,为“全部”定义了一个开关参数,因为我假设不需要该顺序。
[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,这很有意义。