Benutzer:MovGP0/Powershell/CmdletBinding

aus Wikipedia, der freien Enzyklopädie
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      


CmdletBinding

Verbose and Debug
[CmdletBinding()]
param(
   # [Parameter(Mandatory= ..., ValueFromPipeline= ..., Position=...)]
   # [Type]$param = $defaultValue
)

process {
   $debug = ($PSBoundParameters['Debug'] -eq $true)
   $verbose = ($PSBoundParameters['Verbose'] -eq $true)
   Some-Command -Debug:$debug -Verbose:$verbose
}
WhatIf
Function Do-Stuff {
    [CmdletBinding(SupportsShouldProcess=$true)]
    param([string[]]$Objects)
 
    process {
        ForEach($item in $Objects) {
            if ($pscmdlet.ShouldProcess("$item", "DoStuff")) {
                Write-Host "Actually performing $Action on $item"
            }
        }
    }
}
WhatIf and Confirm
function Stop-CompanyXyzServices {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    Param(
        [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]      
        [string]$Name
    )

    process {
        if($PSCmdlet.ShouldProcess($env:COMPUTERNAME,"Stop XYZ services '$Name'")){  
            ActualCmdletProcess
        }
        if([bool]$WhatIfPreference.IsPresent){
            ActualCmdletProcess
        }
    }
}

function ActualCmdletProcess{
# add here the actual logic of your cmdlet, and any call to other cmdlets
    Stop-Service $name -WhatIf:([bool]$WhatIfPreference.IsPresent) -Confirm:("Low","Medium" -contains $ConfirmPreference)
}