How to add -confirm:$false in a powershell hashtable?

Viewed 552
$cmdlet="Disable-RemoteMailBox"
$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive=""}
$command_args=""
$arguments.keys | ForEach-Object{
    $message = '-{0} {1} ' -f $_, $arguments[$_]
        $command_args+= $message
}
$result=& $cmdlet @arguments 2>&1

In the end this is executed:

Disable-RemoteMailBox -Identity abc@corp.com -DomainController dc.corp.local -Archive 

but i need to add a confirm:$false

Disable-RemoteMailBox -Identity abc@corp.com -DomainController dc.corp.local -Archive -Confirm:$false

How to add this $false in the Hashtable?

2 Answers

Change the $arguments hashtable from:

$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive=""}

to

$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive="";Confirm=$false}

Adding to Mathias's concise answer

Excepting for the confirm functionality's integration with the $ConfirmPreference preference variable, the -Confirm common parameter can be looked at as a simple switch parameter. It is either present or not present. However, PowerShell's internal type conversion engine will evaluate a [Switch] more like a [Boolean] You can see this if you cast a [Bool] to a [Switch].

[Switch]$true or [Switch]$false will return IsPresent True/False respectively.

If you specify Confirm = $false in a splatting hash table, the type coercion (casting) that occurs during the parameter binding will handle it correctly. This is also true for any other switch parameter, even custom ones you define in your custom functions. This type conversion is also noticiable when you need to evaluate a switch parameter internal to a function.

If I specify a switch parameter named $Delete

Param( [Switch]$Delete )

Then internally I can execute logic like:

If( $Delete -eq $true ) {
    # Delete the file or whatever...
}

Of course, you can shorten to:

If( $Delete ) {
    # Delete the file or whatever...
}

However, you don't need a deep understanding of PowerShell's type conversion system to use Boolean or Switch parameters in splatting hash tables. It's documented in about_Splatting. The first few lines will explain hash table splatting of switch parameters.

Related