0
0
PowerShellscripting~30 mins

WhatIf and Confirm support in PowerShell - Mini Project: Build & Apply

Choose your learning style9 modes available
WhatIf and Confirm support
📖 Scenario: You are creating a PowerShell script to safely delete files. You want to add safety features so users can see what will happen before files are deleted and confirm the action.
🎯 Goal: Build a PowerShell script that supports -WhatIf and -Confirm parameters to safely delete files.
📋 What You'll Learn
Create a function called Remove-MyFile that deletes a file.
Add [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')] to enable -WhatIf and -Confirm support.
Use $PSCmdlet.ShouldProcess() to check if the action should proceed.
Use Write-Verbose to show a message when deleting a file.
Test the function with -WhatIf and -Confirm parameters.
💡 Why This Matters
🌍 Real World
PowerShell scripts often delete files or make changes that can be risky. Using WhatIf and Confirm lets users preview or approve actions to avoid mistakes.
💼 Career
Many IT and automation jobs require writing safe scripts that support WhatIf and Confirm to prevent accidental data loss.
Progress0 / 4 steps
1
Create the Remove-MyFile function
Create a PowerShell function called Remove-MyFile that takes a parameter Path and deletes the file at that path using Remove-Item.
PowerShell
Need a hint?

Use Remove-Item -Path $Path inside the function to delete the file.

2
Add CmdletBinding to support -WhatIf and -Confirm
Add [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')] above the param block in the Remove-MyFile function to enable -WhatIf and -Confirm support.
PowerShell
Need a hint?

Place [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')] right before the function keyword.

3
Use $PSCmdlet.ShouldProcess() to confirm action
Inside the Remove-MyFile function, replace the direct Remove-Item call with a check using if ($PSCmdlet.ShouldProcess($Path, 'Remove file')). Only call Remove-Item if this returns true. Also add Write-Verbose to show a message before deleting.
PowerShell
Need a hint?

Use if ($PSCmdlet.ShouldProcess($Path, 'Remove file')) { ... } to check before deleting.

4
Test the function with -WhatIf and -Confirm
Call Remove-MyFile with -Path set to "C:\temp\test.txt" and add the -WhatIf parameter to see what would happen. Then call it again with -Confirm to ask for confirmation.
PowerShell
Need a hint?

Run Remove-MyFile -Path "C:\temp\test.txt" -WhatIf and Remove-MyFile -Path "C:\temp\test.txt" -Confirm to test.