quarta-feira, 6 de novembro de 2019

Powershell - Functions Parameters


Functions Parameters


 CMDLETBINDING() parameter clause

According to the help for “CmdletBinding”, it makes [functions and scripts] operate like compiled cmdlets that are written in C#, and it provides access to features of cmdlets. Adding “[CmdletBinding()]” at the front of our script will give us access to advanced features.


Basic parameter clause

        [String]$LogFolder,
or
        [String]$LogFolder="C:\temp" #Default Value
or
        [String[]] $MenuItemsList=@("Menu 01","Menu 02","Menu 03") #Array of Strings
or
        [PSCredential]$Credentials

Alias parameter clause

        [Alias('Computer')]

Position parameter clause

       [Parameter(Position=0)]

Mandatory parameter clause

        [Parameter(Mandatory)]

HelpMessage parameter clause

        [(HelpMessage='Please enter a computername')]


ParameterSetName parameter clause

#Used to group parameters
        [CmdletBinding(DefaultParameterSetName="All")]

        [switch]$OptionDefault,

        [Parameter(ParameterSetName='One')]
        [switch]$Option1,

        [Parameter(ParameterSetName='One')]
        [string]$SubOption1Only,

        [Parameter(ParameterSetName='Two')]
        [switch]$Option2,
       
        [Parameter(ParameterSetName='Two')]
        [string]$SubOption2Only,

        [Parameter(ParameterSetName='One')]
        [Parameter(ParameterSetName='two',Mandatory=$true)]
        [string]$SubOption1and2


Validation parameter clause

        [ValidateRange(2,7)]
or
        [ValidateSet(“Test”,"Dev","Prod")]
or
        [ValidateNotNullOrEmpty()]
or
        [ValidateScript({Test-Path $_ -PathType ‘Container’})]
or
        [ValidateScript({
         if (Test-Connection -ComputerName $_ -Quiet -Count 1) {
             $true
           } else {
              throw "The computer $($_) is not available."
           }
         })]



Example:

[CmdletBinding()]
Param(         
        [Parameter(Mandatory=$false)]
        [String]$LogFolder,

        [Parameter(Mandatory=$true)]
        [ValidateSet(“Test”,"Dev","Prod")]
        [String]$Environment,

        [Parameter(Mandatory=$true)]
        [ValidateScript({Test-Path $_ -PathType ‘Container’})]
        [String]$ServerListFile, 

        [Parameter(Mandatory=$False)]
        [PSCredential]$Credentials
       
        [Parameter(Mandatory=$False)]
        [String[]] $MenuItemsList=@("Menu 01","Menu 02","Menu 03")

)

Nenhum comentário:

Postar um comentário