I've been thinking about how to effectively manage updates to ADUsers in PowerShell. I have a variable called $DoWork, and I know I can use -WhatIf for testing purposes with ADUser commands. My question is whether I can incorporate this variable into my commands like this: `Set-ADuser $Actions -WhatIf:$DoWork`, or if I need to structure it differently with an if statement, like: `if($DoWork) {Set-ADuser $Actions} else {Set-ADuser $Actions -WhatIf}`. What's the best way to set this up?
5 Answers
If $DoWork is a Boolean variable, then your idea is on point. But keep in mind that if other actions rely on changes being made to AD, those changes won’t occur if you use -WhatIf. It might be better to leverage ShouldProcess for your functions.
You could also consider using `Set-ADuser $Actions -WhatIf:$WhatIfPreference`. This might be another approach depending on how you want to manage it.
The -WhatIf parameter is actually just for testing. It gives you a preview of what your command would do if it ran. Just remember, sometimes it doesn't work as expected, and changes might still be applied, so be cautious!
Sounds like you might want to look into using Try, Catch, Finally statements. This lets your command try to execute, catch any errors (and log them), and do something in the end regardless of what happened during the try block. However, from what you've said, I get that you're aiming for an audit mode functionality where it would run the -WhatIf when in that mode.
Right! I have plenty of try/catch/finally in my script already. Basically, I want to run it in audit mode to preview the changes beforehand without making any real updates.
Both approaches you mentioned could work. However, you could flip your logic to use -not since $DoWork is a Boolean. So, it would look like this: `Set-ADUser $Actions -WhatIf:(-not $DoWork)`. If you've got a Boolean $TestMode at the start of your script, it would simplify things since you wouldn't need to negate it there.
Yeah, I've had that happen too. Always double-check before running any commands!