I've been curious about how to use the -WhatIf parameter in PowerShell, particularly when working with ADUsers. I want to run updates based on whether a variable called $DoWork is true or false. Instead of using a simple if-else structure, I'm looking for a way to directly incorporate -WhatIf into my command, like `Set-ADuser $Actions -WhatIf:$DoWork`. Is that feasible, or should I stick to something like `if($DoWork) {Set-ADuser $Actions } else {Set-ADuser $Actions -WhatIf}`?
2 Answers
You're mixing two different concepts here. The IF statement checks if a condition is true or false, whereas -WhatIf performs a dry run of your commands. You can find more details about this in various PowerShell documentation, including some helpful blog posts as well.
You might want to consider doing something like this:
```powershell
$AmITesting = $True
$WhatIfPreference = $AmITesting
```
This way, -WhatIf will be enabled for any command that supports it. If you set $AmITesting to $False, you won't have to worry about it running in WhatIf mode. I used to do the typical if-else approach, but it became tedious over time! Just be cautious, as not every command supports -WhatIf.
To give a clearer picture, a typical -WhatIf usage would look like this:
```powershell
function Remove-File {
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'high')]
param (
[Parameter(Mandatory)]
[string]$Path
)
if ($PSCmdlet.ShouldProcess($Path, "Remove")) {
'I removed the item'
}
}
Remove-File 'c:somefile.txt' -WhatIf
```
But keep in mind that not all developers implement this correctly, which could lead to unexpected behavior.