PowerShell for Windows Admins

Feb 5 2012   3:22PM GMT

Passing no parameters

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

This was interesting question on the forum – user wants to retrieve something by name or id and if neither are given then return all objects.  This is similar to

Get-Process powershell
Get-Process -Id 1568

In the first two we filter on a name or id – in the last one we get everything


This is what I arrived at using processes as an example

function test-proc{             
param (             
switch ($psCmdlet.ParameterSetName) {            
 "ByName"  {Get-Process -Name $name }            
 "ById"  {Get-Process -Id $id }            
 "XXXXX" {Get-Process }            

The trick is to define a default parameter set with no parameters – then when you don’t use any parameters it kicks in at the switch statement and your code can run as required

Be interested if this gets broken in any scenarios as it seems to simple to be correct – but it works

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: