Mandatory Parameter with a Dialog

by Feb 6, 2014

Typically, when you mark a function parameter as "mandatory", PowerShell will prompt the user when the user omits the parameter:

function Get-Something
{
      param
      (
            [Parameter(Mandatory=$true)]
            $Path
      )

      "You entered $Path"
} 

The result looks like this:

Here is an alternative: if the user omits -Path, the function opens an OpenFile dialog:

function Get-Something
{
      param
      (
            $Path = $(
              Add-Type -AssemblyName System.Windows.Forms
              $dlg = New-Object -TypeName  System.Windows.Forms.OpenFileDialog
              if ($dlg.ShowDialog() -eq 'OK') { $dlg.FileName } else { throw 'No Path submitted'}
            )
      )

      "You entered $Path"
} 

Twitter This Tip! ReTweet this Tip!