Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$pscmdlet.ShouldProcess(...) returns "Yes" or "Yes to All"

Tags:

powershell

I'm writing a script to create VMs, and obviously I would like to support the standard confirm/whatif semantics. However, if I have a number of machines to create, it would be good if I could differentiate between "Yes" and "Yes to All" so I don't necessarily have to reconfirm every machine.

$pscmdlet.ShouldProcess only returns a boolean, so how can I tell the difference?

like image 902
user103633 Avatar asked Sep 21 '10 19:09

user103633


1 Answers

Here's an example function that accepts pipeline input for the computer name and implements the behaviour you desire:

function set-something {
    [cmdletbinding(SupportsShouldProcess=$true)]
    param(
        [parameter(position=0, valuefrompipeline=$true)]
        $Computer,
        [parameter(position=1)]
        $Value
    )

    process {
        if ($pscmdlet.shouldprocess("Are you sure?")) {        
            write-host "setting machine $computer to $value"
        }
    }
}

"srv1","srv2","srv3" | set-something -value 42 -confirm

If you answer "yes" you will be prompted for the next machine. If you answer "yes to all" you will no longer be prompted. The important part is that you use pipeline input - this causes the function to be executed as a whole only once, but the process block within the function is invoked once for each incoming element in the pipeline. This lets it remember the "yes for all" and will not prompt on subsequent process block invocations. Make sense?

UPDATE: it's not required to use a pipeline for this to work. The important thing is that the function must be able to keep state, so passing all input in an array or collection as a parameter would work too. In this case, you would loop over the $computer collection yourself. With a pipeline, effectively the shell loops for you.

like image 182
x0n Avatar answered Sep 22 '22 21:09

x0n