Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I have a .ps1 with this content (the actual content does not matter) :

param(
    [Parameter(Mandatory=$true)]
    [string]
    $someArgument
)

# Do something risky
Remove-Item "c:\path\$someArgument.txt"

I'd like to add to my script (or to any method in fact) a confirmation message, that can be switch off (on by default).

.\myscript.ps1 "foo" -Confirm:$false

How can I do that ?

share|improve this question
up vote 3 down vote accepted

With Advanced functions, you can use something called ShouldProcess.

At the top of your script, you can add an attribute called [CmdletBinding]

[CmdletBinding(

        SupportsShouldProcess=$true,

        ConfirmImpact="High"

    )]

Once you have that, in the body of your function, you need to use an if statement

if ($pscmdlet.ShouldProcess($thingIamGoingToChange))

Take a look at help about_advanced_functions and help about_functions_cmdletbinding.

share|improve this answer
    
Thanks! I'll have to dive into the possibilities of CmdLetBinding... guessing I can go far further with it :) – Steve B Apr 26 '12 at 15:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .