Feb 5 2012 3:22PM GMT
Posted by: Richard Siddaway
PowerShell
Passing no parameters
Posted by: 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
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




