1

I'm trying to port some perl code to powershell. However, I don't know how to implement optional arguments in powershell?

In perl, My code does something like this below, which allows me to call the script as:

myscript -z -in myin

or with optional argument:

myscript -z myz -in myin

Here's how I do this in perl:

#!/usr/local/bin/perl
# PERL CODE
use Getopt::Long;

GetOptions(
    'z:s'   => \$zip,
    'h'     => \$help,
    'in=s'  => \$input_dir,
);

# Using a colon (:s) instead of the equals sign (=s) 
# indicates that the option value is optional. In 
# this case, if no suitable value is supplied, 
# string valued options get an empty string ''.

However in powershell i'm not sure how to get the functionality of ":s" in perl. Here's my Powershell code that attempts to do the same thing:

# Powershell
param(
    [string] [optional???] $zip = "hello",
    [switch]$h,
    [string]$input_dir
)

Is there a way to do this in powershell?

pico
  • 1,660
  • 4
  • 22
  • 52
  • Unfortunately, PowerShell (as of v7.2) does _not_ have support for parameters whose argument is _optional_. A - suboptimal - _workaround_ is available for a _single_ parameter of this type. See the [linked duplicate](https://stackoverflow.com/questions/58838941/powershell-special-switch-parameter). – mklement0 Jan 06 '22 at 20:47

1 Answers1

1

Powershell parameters are optional by default. Mandatory parameters need to be marked with [parameter(Mandatory=$true)]. See also about_functions_Advanced_Parameters in Microsoft docs.

Markus
  • 63
  • 2
  • 7
  • 1
    Not the Parameter... the Argument to the parameter... For example, given parameter "-z myz", the "myz" part is the argument to the parameter "-z". I want to know if I can my "myz" optional but still have "-z" – pico Jan 06 '22 at 20:41
  • Passing an empty string is still acceptable unless you have `[NotNullOrEmpty]` as well. Alternatively you could specify another parameter set with that parameter as a switch instead. The link provided may give you enough to do so. – carrvo Jan 07 '22 at 03:37