0

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 }
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Hausec
  • 37
  • 7
  • 2
    Possible duplicate of [How do I pass multiple parameters into a function in PowerShell?](https://stackoverflow.com/questions/4988226/how-do-i-pass-multiple-parameters-into-a-function-in-powershell) – Owain Esau Oct 04 '18 at 01:35
  • You can try `./script.ps1 -option "local" file1,file2,file3` and `$option` will take the value `"local"`. – JPBlanc Oct 04 '18 at 04:20

1 Answers1

2

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'
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328