I\'m trying to take user input and before proceeding I would like get a message on screen and than a confirmation, whether user wants to proceed or not. I\'m using the follo
Here is the documentation from Microsoft on how to request confirmations in a cmdlet. The examples are in C#, but you can do everything shown in PowerShell as well.
First add the CmdletBinding
attribute to your function and set SupportsShouldProcess
to true
. Then you can reference the ShouldProcess
and ShouldContinue
methods of the $PSCmdlet
variable.
Here is an example:
function Start-Work {
<#
.SYNOPSIS Does some work
.PARAMETER Force
Perform the operation without prompting for confirmation
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
# This switch allows the user to override the prompt for confirmation
[switch]$Force
)
begin { }
process {
if ($PSCmdlet.ShouldProcess('Target')) {
if (-not ($Force -or $PSCmdlet.ShouldContinue('Do you want to continue?', 'Caption'))) {
return # user replied no
}
# Do work
}
}
end { }
}
Write-Warning "This is only a test warning." -WarningAction Inquire
from: https://serverfault.com/a/1015583/584478
write-host
does not have a -confirm
parameter.
You can do it something like this instead:
$caption = "Please Confirm"
$message = "Are you Sure You Want To Proceed:"
[int]$defaultChoice = 0
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Do the job."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Do not do the job."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$choiceRTN = $host.ui.PromptForChoice($caption,$message, $options,$defaultChoice)
if ( $choiceRTN -ne 1 )
{
"Your Choice was Yes"
}
else
{
"Your Choice was NO"
}
Read-Host
is one example of a cmdlet that -Confirm
does not have an effect on.-Confirm
is one of PowerShell's Common Parameters specifically a Risk-Mitigation Parameter which is used when a cmdlet is about to make a change to the system that is outside of the Windows PowerShell environment. Many but not all cmdlets support the -Confirm
risk mitigation parameter.
As an alternative the following would be an example of using the Read-Host
cmdlet and a regular expression test to get confirmation from a user:
$reply = Read-Host -Prompt "Continue?[y/n]"
if ( $reply -match "[yY]" ) {
# Highway to the danger zone
}
The Remove-Variable
cmdlet is one example that illustrates the usage of the -confirm
switch.
Remove-Variable 'reply' -Confirm
Additional References: CommonParameters, Write-Host, Read-Host, Comparison Operators, Regular Expressions, Remove-Variable