PowerShell has built-in functionality for all of its cmdlets and advanced functions, known as the WhatIf parameter. The WhatIf parameter allows you to see what your script or function would have done if it were to have run.

Have you ever hit the Enter key on the keyboard and immediately regretted the decision? We've all been there. We've built this beautiful script that automates all kinds of tasks, and we're excited to try it out. The script runs while you forgot a few minor details, which unfortunately leads to user account deletions, mailbox permission problems, servers going down… You get the drift here.

It'd be good to know what the code would have done if it were actually to have run. Next time, instead of testing in production, why not incorporate WhatIf functionality into your code?

Granted, it's up to you to add this functionality into your code, so we've still got human error to worry about. But it's a safe step in the right direction.

Let's create an example of a function that would be catastrophic if it ran.

function Invoke-AdUserCleanup {

    $inactiveUsers = Search-ADAccount -AccountInactive -UsersOnly -TimeSpan "$OlderThan.00:00:0"
    $inactiveUsers | Remove-AdUser -Confirm:$false

Let's say this function is part of a large script you've created to clean up old user accounts. One day you're tired and accidentally forget a single keystroke. Instead of typing 30 to represent cleaning up users older than 30 days, you miss the zero and type 3 instead.

Your script doesn't know you missed a keystroke and happily goes along and begins removing all Active Directory users older than three days. I'm sure a lot of your user accounts fall in this category. Adding a failsafe could have prevented this. One of those failsafes is WhatIf support.

To make this function a little safer, I'm going to add WhatIf support. This will allow me to invoke this function using the WhatIf parameter.

PS> Invoke-AdUserCleanup -OlderThan 3 -WhatIf

Adding WhatIf functionality to your function requires two steps.

  • Adding the SupportsShouldProcess keyword
  • Adding the $PSCmdlet.ShouldProcess conditional statement

Without both of these requirements, WhatIf will not work. First, we must add SupportsShouldProcess inside of CmdletBinding() at the top. This tells PowerShell that this function is going to be an advanced function that supports the WhatIf parameter.


Next, we must add a conditional step right before the potentially destructive action. We do this by checking for WhatIf usage. And to do that, we monitor the output of the ShouldProcess() method on the automatic $PSCmdlet variable. The ShouldProcess() method has a few arguments, but the most useful look like this:


You can see here that we specify the target of the action we're about to perform and also a description of the action we'll be performing. If we use WhatIf when calling this function, this method will return $true.

For our example, we're removing an Active Directory user, so our target will be the individual user account, and our action will be 'Remove.' We can show this then by passing this information to the ShouldProcess() method.

function Invoke-AdUserCleanup {

    $inactiveUsers = Search-ADAccount -AccountInactive -UsersOnly -TimeSpan "$OlderThan.00:00:0"
    $inactiveUsers | foreach {
        if ($PSCmdlet.ShouldProcess($_.Name,'Remove')) {
            $_ | Remove-AdUser -Confirm:$false

Notice that I've changed up the code a bit in our final function. This allows me to confirm each user account. If you'd rather not see every user account it will potentially remove, you could have left it as is. However, when I run the function with the WhatIf parameter now, it doesn't do a thing. It just returns text to the console of what the function would have done if it ran without WhatIf.

Subscribe to 4sysops newsletter!

WhatIf example

WhatIf example

  1. Jim 5 years ago

    I'm curious - you commented out the line that does the actual remove:

    #$_ | Remove-AdUser -Confirm:$false

    I'll look up the details later, but is that part of adding the What-If functionality?

  2. Andrew 2 years ago

    "If we use WhatIf when calling this function, this method will return $true." Isn't the opposite true? Using WhatIf should prevent the critical block from executing.

  3. Tim Köhler 1 year ago

    Hi Adam,
    could you please have a look; somehow I have no output while using -whatif

    Thanks in advance.

                function DeleteFolder{
                #Get UserB credential
                $Credential =  $cred_svc #Get-Credential itdroplets\UserB
                #Use System.Diagnostics to start the process as UserB
                $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
                #With FileName we're basically telling powershell to run another powershell process
                $ProcessInfo.FileName = "powershell.exe"
                #CreateNoWindow helps avoiding a second window to appear whilst the process runs
                $ProcessInfo.CreateNoWindow = $true
                #Note the line below contains the Working Directory where the script will start from
                $ProcessInfo.WorkingDirectory = $path
                $ProcessInfo.RedirectStandardError = $true 
                $ProcessInfo.RedirectStandardOutput = $true 
                $ProcessInfo.UseShellExecute = $false
                #The line below is basically the command you want to run and it's passed as text, as an argument
                $ProcessInfo.Arguments = "$PSCmdlet.ShouldProcess($FolderToDelete,'Remove'){Remove-Item -LiteralPath $FolderToDelete -Force -Recurse -Verbose}"   # "Get-Process Explorer"
                #The next 3 lines are the credential for UserB, as you can see, we can't just pass $Credential
                $ProcessInfo.Username = $Credential.GetNetworkCredential().username
                $ProcessInfo.Domain = $Credential.GetNetworkCredential().Domain
                $ProcessInfo.Password = $Credential.Password
                #Finally start the process and wait for it to finish
                $Process = New-Object System.Diagnostics.Process 
                $Process.StartInfo = $ProcessInfo 
                $Process.Start() | Out-Null 
                #Grab the output
                $GetProcessResult = $Process.StandardOutput.ReadToEnd()
                #Print the Job results
                DeleteFolder -whatif


    Got the Code from: https://www.itdroplets.com/run-a-command-as-a-different-user-in-powershell/

Leave a reply

Please enclose code in pre tags

Your email address will not be published. Required fields are marked *


© 4sysops 2006 - 2021


Please ask IT administration questions in the forums. Any other messages are welcome.


Log in with your credentials


Forgot your details?

Create Account