0

Suppose you have a PowerShell script that takes a variable number of arguments. You want to treat anything that isn't an option as a filename. In Bash, this is easy:

files=() # Empty array of files

while [ $# -gt 0 ]
do
    case "$1" in
        -option1) do_option1=true ;;
        -option2) option2_flag="$2" shift ;;
        *) # Doesn't match anything else
            files+=("$1") ;;
    esac
    shift
done

What would be the equivalent code using PowerShell's Param()? It's useful for eliminating much of the boilerplate parsing code, but how would I use it to parse the files? For example, this works:

Param(
    [switch]$Option1,
    [string]$Option2,
    [string[]]$Files
);

but you have to call the script like script.ps1 the,file,names to get it parsed correctly. If you call script.ps1 the file names it won't get recognized.

I also tried $PSBoundParameters, but that didn't work either.

Why is this happening and how can I fix this? Thanks!

James Ko
  • 32,215
  • 30
  • 128
  • 239

1 Answers1

0

Use Mandatory=$True for your file name parameter and Mandatory=$False for your options.

Param(
    [Parameter(Mandatory=$false)]
    [switch]$Option1,
    [Parameter(Mandatory=$false)]
    [string]$Option2,
    [Parameter(Mandatory=$True)]
    [string[]]$Files
);

So when you call your function, you can do

yourFunc "filename" # only pass value for $files
yourFUnc -option1 "value" -option2 "value" -files "value" # pass value to all of your paras
Bum
  • 89
  • 1
  • 6