PowerShell Smart Parameter Expressions


A while back I posted about how to mark a script parameter as required in PowerShell.  Shortly afterwards, there was some chatter on it that I think makes it worthwhile to add another post on the subject of PowerShell script parameters.

Let’s say you have the question:  “Can I do <X> with a parameter?” 

The answer is probably “Yes”.  🙂

Jim and an anonymous emailer both asked:

Is there any way you can specify a parameter based on the value of another parameter?

The answer is yes.  You can put pretty much any expression in the default evaluator of the parameter definition. For example: param( [switch] $switchparam, #an optional “switch parameter” (ie, a flag) [string] $user = $(if ($switchparam) { Read-Host -prompt “User”}) #prompt user for value if none provided )

In the above example, if –switchparam is specified in the command, the $user parameter default expression will evaluate to true and prompt the user for a user name.

Leave a Reply

Your email address will not be published. Required fields are marked *