Convert perl GetOptions into equivalent Powershell param statement

Viewed 29

Let's say I have some perl code that reads flags from a command line:

#default values
$opt_redflag  = 0;
$opt_blueflag = 0;
$opt_target   = "none";
$opt_type     = "infinite";

%options = (
    'redflag'     => \$opt_redflag,
    'blueflag'    => \$opt_blueflag,
    'target=s'    => \$opt_target,
    'type=s'      => \$opt_type
);

GetOptions(%options);

How would I convert this into the equivalent Powershell param command. I'm thinking it would be this:

param(
    [Parameter(Mandatory=$false)]
    [alias("redflag")]
    [bool]$opt_redflag=$false,

    [Parameter(Mandatory=$false)]
    [alias("blueflag")] 
    [bool]$opt_blueflag=$false,

    [Parameter(Mandatory=$false)]
    [alias("target")]
    [string]$opt_target="none",

    [Parameter(Mandatory=$false)]
    [alias("infinite")]
    [string]$opt_type="infinite"
);

write-host "redflag:  $opt_redflag"
write-host "blueflag: $opt_blueflag"
write-host "target:   $opt_target"
write-host "type:     $opt_type"

exit 1;

however, I get this error:

PS C:\Users\dude> .\setup2.ps1
C:\Users\dude\setup2.ps1 : Parameter set cannot be resolved using
the specified named parameters.
At line:1 char:1
+ .\setup2.ps1
+ ~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [setup2.ps1], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,setup2.ps1
1 Answers

This would be the "Powershell way" of writing it:

param(
    [switch]$Red,
    [switch]$Blue,
    [string]$Target = "none",
    [string]$Type = "infinite"
)

It's as simple as that. You can leave out the "Parameter" attributes, if you're not going to specify any non-defaults. Also, for "Flags" or switches, type [switch] is better suited than bool.

Related