locked
PowerShell v2.0 and command line option parsing beyond $args

    Question

  • I really am not a fan of positional arguments with scripts. Is there something available in PowerShell v2 similar to GetOpts in Perl or OptionParser in Python.

     

    Any help on this would be greatly appreciated.

    Sunday, June 12, 2011 7:22 PM

All replies

  • Parameter handling is provided in PowerShell by default. If you use param() in the first line of your script like this...

    param([string]$Path = "C:\",[string]$Filter = "*.txt",[switch]$Overwrite)
    

    ...then you can call your script several ways using named parameters like this:

    .\Script.ps1 -Path "C:\Temp" -Filter "*.dat" -Overwrite

    .\Script.ps1 -Path "C:\Temp"

    .\Script.ps1 -Filter "*.dat"  -Overwrite -Path "C:\Temp"

    .\Script.ps1 -Overwrite -Filter "*.dat"

    Parameters with defaults can be omitted and since they are named we can provide them in any order.


    Make everything as simple as possible, but not simpler.
    -Albert Einstein
    Wednesday, December 21, 2011 6:37 PM