Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.