Ryvik
Ryvik

Reputation: 473

Calling multiple functions via parameters when running .ps1 script

I have a .ps1 script that has multiple functions in it. Instead of running them all at once, I'd like the user to be able to put in which functions they'd like to run. e.g.: ./script.ps1 -func1 -func2 or ./script.ps1 -All

I can get it to work by just comparing the user inputted parameter to a function name, but the problem is I would like the user to be able to put it in any order.

Here's what I have working now, but I'm not sure if I can optimize it in some way.

[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
}

Instead of just having a bunch of 'if' statements with 'or' conditionals, I just watch the user to input a function as a parameter.

I'm sure there's a way to do it with a switch or array but I'm not a great programmer.

Upvotes: 1

Views: 781

Answers (1)

Guenther Schmitz
Guenther Schmitz

Reputation: 1999

my quick approach is the following. I define a switch parameter per function and one for "all" as i assume that the order is not required.

[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
}

to call the script you can then run

./script.ps1 -Func2

or

./script.ps1 -Func1 -Func2

or

./script.ps1 -All

Upvotes: 2

Related Questions