Apply WhatIf to an entire script

      Comments Off on Apply WhatIf to an entire script

Yesterday, I needed to create a script that would allow me to stop a lot of services in one go, so I created a small one-liner script.
However, as it could be dangerously easy to execute this by mistake, I decided to figure out how to apply WhatIf as a default setting for the script, but still allowing to override it.
This turned out to be surprisingly easy, using the $whatifpreference preference variable:

  [boolean]$whatifpreference = $true
$filter = "DisplayName LIKE 'MyService_%' AND Status = 'Running'"
Get-WmiObject -Class Win32_Service -Filter $filter | ForEach { Stop-Service -DisplayName $_.DisplayName}