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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With