0
0
PowerShellscripting~5 mins

WhatIf and Confirm support in PowerShell

Choose your learning style9 modes available
Introduction

WhatIf and Confirm help you test commands safely before making changes. They prevent mistakes by showing what would happen or asking for approval.

Before deleting files or folders to avoid accidental loss.
When stopping or restarting services to confirm the action.
Before changing system settings to see the impact.
When running scripts that modify important data.
To get a preview of changes without applying them.
Syntax
PowerShell
Cmdlet-Name -WhatIf
Cmdlet-Name -Confirm

-WhatIf shows what the command would do without doing it.

-Confirm asks you to approve each action before it runs.

Examples
This shows what would happen if you delete the file, but does not delete it.
PowerShell
Remove-Item -Path "C:\Temp\file.txt" -WhatIf
This asks you to confirm before stopping the Print Spooler service.
PowerShell
Stop-Service -Name "Spooler" -Confirm
This asks for confirmation before deleting the file.
PowerShell
Remove-Item -Path "C:\Temp\file.txt" -Confirm
Sample Program

This function uses both -WhatIf and -Confirm. -WhatIf takes precedence, so it shows what would happen without prompting for confirmation or performing the action.

PowerShell
function Remove-MyFile {
    param(
        [string]$Path
    )
    Remove-Item -Path $Path -WhatIf -Confirm
}

Remove-MyFile -Path "C:\Temp\example.txt"
OutputSuccess
Important Notes

Not all cmdlets support -WhatIf and -Confirm. Check the cmdlet help.

You can force confirmation with -Confirm:$true or skip it with -Confirm:$false.

-WhatIf is great for testing scripts safely before running them.

Summary

-WhatIf shows what a command would do without doing it.

-Confirm asks you to approve actions before they happen.

Use them to avoid mistakes and test commands safely.