Using -WhatIf with Conditional Logic in PowerShell

0
2
Asked By CuriousCoder92 On

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

Answered By TechieTom84 On

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.

Answered By ScriptingSally77 On

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.

DevDude53 -

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.