Search code examples
powershellparameter-passingpowershell-2.0powershell-3.0

Embedding parameters to a switch


I have a .ps1 that calls down files and if it can't call down the files, it will look locally for those files. I'd like to give the option, as a parameter, to either work locally or go fetch from the internet and also specify which of the 5 files to use or call down. I'm made the script work with a "local" and "external" function, but how do I also add parameters to those functions?

For example:

./script.ps1 -local file1,file2,file3

or

./script.ps1 -external file4,file5

Here is my code currently:

Param(
    [Parameter(Position=1)][string]$option
)

function RunLocal {
    Write-Host "local"
}
function RunExternal {
    Write-Host "ext"
}
function RunDefault {
    Write-Host "default"
}

switch ($option) {
    local    { RunLocal }
    external { RunExternal }
    default  { RunDefault }
}

Solution

  • I'd define different parameter sets and discriminate by parameter set name.

    [CmdletBinding(DefaultParameterSetName='default')]
    Param(
        [Parameter(ParameterSetName='default', Position=0, Mandatory=$true)]
        [string[]]$Default,
    
        [Parameter(ParameterSetName='external', Position=0, Mandatory=$true)]
        [string[]]$External,
    
        [Parameter(ParameterSetName='local', Position=0, Mandatory=$true)]
        [string[]]$Local
    )
    
    # ...
    
    switch ($PSCmdlet.ParameterSetName) {
        'local'    { RunLocal }
        'external' { RunExternal }
        'default'  { RunDefault }
    }
    
    # Usage:
    # script.ps1 [-Default] 'file1', 'file2'
    # script.ps1 -External 'file1', 'file2'
    # script.ps1 -Local 'file1', 'file2'
    

    Another option would be using separate parameters for option and file list, as JPBlanc suggested, but in that case you should validate the -Option parameter, so that only allowed options can be used:

    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [ValidateSet('default', 'external', 'local')]
        [string]$Option,
    
        [Parameter(Position=1, Mandatory=$true)]
        [string[]]$File
    )
    
    # ...
    
    switch ($Option) {
        'local'    { RunLocal }
        'external' { RunExternal }
        'default'  { RunDefault }
    }
    
    # Usage:
    # script.ps1 'default' 'file1', 'file2'
    # script.ps1 -Option 'default' -File 'file1', 'file2'
    # script.ps1 'external' 'file1', 'file2'
    # script.ps1 -Option 'external' -File 'file1', 'file2'
    # script.ps1 'local' 'file1', 'file2'
    # script.ps1 -Option 'local' -File 'file1', 'file2'