Wednesday, July 30, 2008

Powershell: Confirmation Level

Part of the scripts I'm making for work involve the update of several Exchange Distribution lists in an automated way.
I was on this when I run into an unexpected behavior: the Remove-DistribtionListMember Command was asking for confirmation, even when I had not specified the -Confirm parameter .

A glance to the exchange.ps1 reveled that, in effect, the Powershell environment for exchange has the confirmation Preference set to HIGH by default (thus asking for confirmation on any task that performs a important change to AD)

Changing the confirmation level it's as easy as :

$ConfirmPreference = 'High' # The allowed values seem to be High, Medium, Low, None.


But, I didn't like the idea of changing the value for the whole environment, who knows what would I like to run next ...

So decided to implement a simple temporary variable to store the value of $ConfirmPreference on the script's start and revert it to normal just before the end.

$ConfirmPreference =$OLD_ConfirmPreference

... # My Code here


$OLD_ConfirmPreference =$ConfirmPreference

My next thinking was on how cool would it be to be able to implement a confirmation switch on my own scripts, and I realize that it's easy to do:

Param(
[switch] $Confirm
)

$OLD_ConfirmPreference =$ConfirmPreference

if ($Confirm) {
$ConfirmPreference = 'High'
} else {
$ConfirmPreference = 'None'
}

...... # My Code here

$ConfirmPreference =$OLD_ConfirmPreference



Now I can have (and give to my script users) control on the Powershell confirmations.


No comments: