Using optional parameters and parameter sets

rated by 0 users
This post has 2 Replies | 1 Follower

Not Ranked
Posts 5
Des Posted: 01-31-2012 2:30 AM

I needed to define a PowerShell cmdlet function that optionally accepted different typed parameters; Parameter Sets seemed to be the ideal thing for this, but I struggled to find anything describing how to deal with no parameters. I ended up with the following;

 

function global:Get-SPQuotaTemplate {
    [CmdletBinding(DefaultParameterSetName="none")]

    param(
        [Parameter(ParameterSetName="name",Position=0,ValueFromPipeline=$true)]
        [string]$name,
        [Parameter(ParameterSetName="id",Position=0,ValueFromPipeline=$true)]
        [int]$id,
        [Parameter(ParameterSetName="none",Position=0,ValueFromPipeline=$true)]
        [void]$none
    )

    $contentService = [Microsoft.SharePoint.Adinistration.SPWebService]::ContentService
    switch ($PSCmdlet.ParameterSetName) {
        "name" { $quotaTemplate = $contentService.QuotaTemplates[$name] }
        "id" { $quotaTemplate = $contentService.QuotaTemplates | Where-Object { $_.QuotaID -eq $id } ) }
        default { $quotaTemplate = $contentService.QuotaTemplates }
    }

    return $quotaTemplate
}
Top 25 Contributor
Posts 296
Microsoft MVP
Top Contributor

Reading your code you seem to want to get a QuotaTemplate based on name or id and if you don't get given either than return all templates

Try modifying your code like this example -  I had to use processes as don't have access to SharePoint but principle is the same

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 powershell }
 "ById"  {Get-Process -Name powershell }
 "XXXXX" {Get-Process }
}
}#process
END{}#end
}

If you give a paramter the appropriate parameter set kicks in otherwise the default parameter set is used

Not Ranked
Posts 5

Thanks for that; I tried your suggestion and it works like a charm, although I left the switch statement as it was.

Page 1 of 1 (3 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.