PowerShell for Windows Admins

Feb 5 2012   3:22PM GMT

Passing no parameters



Posted by: Richard Siddaway
Tags:
PowerShell

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
Get-Process

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{             
[CmdletBinding(DefaultParameterSetName="XXXXX")]             
param (             
[parameter(Position=0,            
   ParameterSetName="ByName",            
   ValueFromPipeline=$true,             
   ValueFromPipelineByPropertyName=$true)]            
   [ValidateNotNullOrEmpty()]            
   [string]$name,            
               
   [parameter(Position=0,            
   ParameterSetName="ById",            
   ValueFromPipeline=$true,             
   ValueFromPipelineByPropertyName=$true)]            
   [ValidateNotNullOrEmpty()]            
   [int]$id              
)             
BEGIN{}#begin             
PROCESS{            
            
switch ($psCmdlet.ParameterSetName) {            
 "ByName"  {Get-Process -Name $name }            
 "ById"  {Get-Process -Id $id }            
 "XXXXX" {Get-Process }            
}            
}#process             
END{}#end            
}            
            
##

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.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

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: