PowerShell: Confirm

Discovery

While writing a cmdlet I wanted to be able to use the -Confirm parameter so I could ask for a confirmation when doing something “dangerous”

Description

To enable this feature in a cmdlet you need to add two parameters to the CmdletBinding.

[CmdletBinding(
	SupportsShouldProcess=$True,
	ConfirmImpact="High"
)]

Then you can encapsulate the code to be confirmed in an if-statement checking the $pscmdlet.ShouldProcess("message")

if ($pscmdlet.ShouldProcess($objItem.Name)) {
	#DoStuff
}

Example

Create Remove-Stuff.ps1

<#
.SYNOPSIS
	The Remove-Stuff cmdlet removes stuff
.DESCRIPTION
	The Remove-Stuff cmdlet removes stuff but will ask you before it actually deletes stuff
.PARAMETER Name
	Name of the stuff
.EXAMPLE
	Remove-Stuff "something"
.INPUTS
	System.String
.OUTPUTS
	System.String
#>
[CmdletBinding(
	SupportsShouldProcess=$True,
	ConfirmImpact="High"
)]
Param(
	[Parameter(
		Mandatory = $True,
		Position = 1
	)][string] $Name
)
Begin {}
Process {
	if ($pscmdlet.ShouldProcess($Name)) {
		Write-Output "Daredevil"
	} else {
		Write-Output "Sissy"
	}
}
End {}

Execute the cmdlet and answer “Y”
Confirm-Daredevil
Execute the cmdlet and answer “N”
Confirm-Sissy

Advertisements

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: