Question [Script]Support de -Whatif, -Confirm, -Verbose

Plus d'informations
il y a 18 ans 3 semaines #1777 par Laurent Dardenne
Une petite contribution de Jeffrey Snover, comme sur le blog de l'équipe PowerShell il demande de le publiciter, voilà c'est fait :)
Il en profite pour introduire le raccourcis [REF] ( variable référence, similaire au C# )
[code:1]
# Should-Process.ps1
# Auteur : Jeffrey Snover [MSFT], Windows PowerShell/MMC Architect
# Origine : blogs.msdn.com/powershell/archive/2007/0...bose-in-scripts.aspx
Function Should-Process ($Operation, $Target, [REF]$AllAnswer, $Warning = \"\", [Switch]$Verbose, [Switch]$Confirm, [Switch]$Whatif)
{
# Check to see if \"YES to All\" or \"NO to all\" has previously been selected
# Note that this technique requires the [REF] attribute on the variable.
# Here is an example of how to use this:
# function Stop-Calc ([Switch]$Verbose, [Switch]$Confirm, [Switch]$Whatif)
# {
# $AllAnswer = $null
# foreach ($p in Get-Process calc)
# { if (Should-Process Stop-Calc $p.Id ([REF]$AllAnswer) \"`n***Are you crazy?\" -Verbose:$Verbose -Confirm:$Confirm -Whatif:$Whatif)
# { Stop-Process $p.Id
# }
# }
# }
if ($AllAnswer.Value -eq $false)
{return $false}
elseif ($AllAnswer.Value -eq $true)
{return $true}

if ($Whatif)
{
Write-Host \"What if: Performing operation `\"$Operation`\" on Target `\"$Target`\"\"
return $false
}

if ($Confirm)
{
$ConfirmText = @\"
Confirm
Are you sure you want to perform this action?
Performing operation \"$Operation\" on Target \"$Target\". $Warning
\"@
Write-Host $ConfirmText
while ($True)
{
$answer = Read-Host @\"
[Y] Yes [A] Yes to All [N] No [L] No to all Suspend [?] Help (default is \"Y\"«»)
\"@
switch ($Answer)
{
\"Y\" { return $true}
\"\" { return $true}
\"A\" { $AllAnswer.Value = $true; return $true }
\"N\" { return $false }
\"L\" { $AllAnswer.Value = $false; return $false }
\"S\" { $host.EnterNestedPrompt(); Write-Host $ConfirmText }
\"?\" { Write-Host @\"
Y - Continue with only the next step of the operation.
A - Continue with all the steps of the operation.
N - Skip this operation and proceed with the next operation.
L - Skip this operation and all subsequent operations.
S - Pause the current pipeline and return to the command prompt. Type \"exit\" to resume the pipeline.
\"@ } # clause switch
} #switch
}#While
}#if
if ($Verbose)
{
Write-Verbose \"Performing `\"$Operation`\" on Target `\"$Target`\".\"
}
return $true
} #Should-Process
[/code:1]

Tutoriels PowerShell

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.050 secondes
Propulsé par Kunena