====== Eigene Funktion WhatIf und Confirm ====== Mit Hilfe von [CmdletBinding()] lassen sich die Standardparameter von Powershell einbinden. Möchte man die Parameter WhatIf und Confirm verwenden, muss man beim CmdletBinding Werte übergeben ===== WhatIf ===== Beispielfunktion: function HelloWorld{ [CmdletBinding(SupportsShouldProcess=$True)] param( [Parameter(Mandatory=$True)][System.String]$Greeting ) begin{} process{ if ($PSCmdlet.ShouldProcess("Parameter ausgeben")){ Write-Host $Greeting; } } end{} } Diese Beispielfunktion gibt den String aus, den man mit dem Parameter **Greeting** übergibt. Beispiel: PS C:\Powershell> HelloWorld -Greeting "Bon Jour!" Bon Jour! Wenn man jetzt den Parameter WhatIf übergibt, führt die Powershell den Befehl nicht aus, sondern beschreibt, was wir zuvor angegeben haben: PS C:\Powershell> HelloWorld -Greeting "Hallo!" -WhatIf What if: Performing the operation "HelloWorld" on target "Parameter ausgeben". ===== Confirm ===== Möchte man zusätzlich gefragt werden, ob eine Aktivität ausgeführt werden darf (Z.B. Löschen, Ändern von Dingen, o.ä.), kann man den Confirm-Level mit übergeben: function HelloWorld{ [cmdletBinding(SupportsShouldProcess=$True,ConfirmImpact='High')] ... Standardmäßig fragt die Powershell immer dann nach, wenn das in einer Funktion oder Cmdlet angegebene Confirm-Level gleich oder höher ist als das gegenwertig in der Session angegebene Confirm-Level ($ConfirmPreference). Möglich sind die Werte 'None', 'Low', 'Medium' und 'High' Testet man die so angepasste Funktion erneut aus, fragt die Powershell explizit nach: PS C:\Powershell>HelloWorld -Greeting "Aloha!" Confirm Are you sure you want to perform this action? Performing the operation "HelloWorld" on target "Parameter ausgeben". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): Y Aloha! [[https://4sysops.com/archives/confirm-confirmpreference-and-confirmimpact-in-powershell/|Quelle]], [[https://bcthomas.com/2019/01/adding-whatif-and-confirm-parameters-to-your-powershell/|Quelle2]] {{tag>[Powershell WhatIf Confirm]}}