The PowerShell WhatIf Parameter: Looking Before you Leap

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

PowerShell WhatIf Parameter is a command that allows you to run PowerShell commands, but in many cases it’s just easier to do this with a regular text editor and copy-paste the new result. This tip will show you how to use PowerShell WhatIf parameter so that your scripts don’t need any additional editing afterward.

The “which parameter would you use in order to preview the effects of a powershell command” is a question that comes up often. The PowerShell WhatIf Parameter allows users to preview the effects of a powershell command before executing it.

The PowerShell WhatIf Parameter: Looking Before you Leap

“I don’t always test my scripts in production, but when I do, I do it.”

Don’t make any false statements. It’s something you’ve done before. We’ve all done it at some point. When executing PowerShell scripts in production, however, it does not have to be dangerous. Just remember to utilize the WhatIf parameter in PowerShell!

Wouldn’t it be good to know what a PowerShell command does before it modifies your environment? Imagine having the ability to ask your command, “What would you do if you had to flee?” The WhatIf argument may be used.

A argument named WhatIf is included in all built PowerShell cmdlets. This option allows you to determine if a command will operate as expected or will cause a nuclear catastrophe.

Not only are all built-in cmdlets supported by the WhatIf argument, but so are your scripts and sophisticated functions! If your code may cause changes in your environment, a fail-safe technique is available to you if you want to use it.

Prerequisites

This is going to be a walkthrough post. You should have a few items ready if you want to follow along on this adventure.

I’ll be using Visual Studio Code 1.38 (August 2019) on a Windows 10 computer in this post.

Defined in the WhatIf PowerShell parameter

In a nutshell, the WhatIf parameter is a switch parameter that comes standard with all advanced functions and cmdlets (by adding the PowerShell CmdletBinding keyword to scripts and functions). The command reports the intended consequence of the command to the console when it is invoked. However, it does not really carry out the order.

The WhatIf argument is accessible in all cmdlets and advanced functions. We’ll use the Get-Service, Stop-Service, and New-Item cmdlets to show this argument in this post.

Powershell is being looked for. Support WhatIf

If you’re unsure if a command supports WhatIf, there are two simple methods to find out.

Using the Get-Command command

The Syntax argument of the Get-Command command may be used to see command metadata, as illustrated below. WhatIf is supported if you see a -WhatIf reference.

The-PowerShell-WhatIf-Parameter-Looking-Before-you-LeapGet-Command <CommandName> -Syntax

Tab Completion is a technique for quickly completing a task.

You can also use tab-completion to check whether the WhatIf option is supported. In a PowerShell terminal, enter the command you want to verify, followed by a space, dash, ‘Wh’, and the tab key.

If the word WhatIf occurs in the command, you know it contains the WhatIf parameter.

1647500643_645_The-PowerShell-WhatIf-Parameter-Looking-Before-you-LeapPS> <CommandName> -Wh[tab]

Using the WhatIf Parameter in PowerShell with Cmdlets

The WhatIf parameter may be used in a variety of ways. In this part, you’ll learn how to utilize the WhatIf argument with built-in cmdlets right away.

Creating a Document

The WhatIf argument is included in the New-Item cmdlet, as it is in other cmdlets. You’ll use the New-Item cmdlet to create a file called newfile1.txt in the same working directory in this example.

If you execute the command below, it will generate a file named newfile.txt.

PS51> New-Item -ItemType File -Path .newfile1.txtPS51> New-Item -ItemType File -Path .newfile1.txt

But what if this command generates a file that, if generated incorrectly, may cause a problem? It’s no issue. The WhatIf argument may be added at the end.

-WhatIf New-Item -ItemType File -Path.newfile1.txt-WhatIf New-Item -ItemType File -Path.newfile1.txt

Putting a Service on Hold

The WhatIf option may likewise be used with the Stop-Service cmdlet. In this example, you’ll acquire a list of the first five services and use the Stop-Service command to stop them. You, on the other hand, are not.

Instead, you’ll receive a message in the PowerShell console that tells you which services the Stop-Service cmdlet has halted.

PS51> (Get-Service)[0..4] | Stop-Service -WhatIfPS51> (Get-Service)[0..4] | Stop-Service -WhatIf

Powershell Modifications What If People Behaved Differently Around the World?

You should understand that utilizing the WhatIf argument with a cmdlet or advanced function merely mimics the operation at this stage. At the command level, you were changing WhatIf behavior.

By altering the automatic variable $WhatIfPreference, the WhatIf behavior may be adjusted at a higher level that impacts all instructions.

$WhatIfPreference is a boolean variable. There are just two options: True or False. It is set to False by default, which means that WhatIf support is disabled for all commands unless it is changed at the command level. If True, any commands that support it, regardless of whether they use the WhatIf argument explicitly or not, will be in “WhatIf mode.”

You may check this by using $WhatIfPreference = $true to set the value of $WhatIfPreference to True. As you can see in the example below, New-Item without the WhatIf argument now behaves as if the parameter had been supplied.

PS51> $WhatIfPreference = $truePS51> $WhatIfPreference = $true

Don’t forget to adjust $WhatIfPreference back to False with $WhatIfPreference = $false if you set it to True.

You learnt how to utilize WhatIf support with existing cmdlets in this part. You’ll learn how to include WhatIf support in your own scripts and functions in the following step.

Putting Powershell into Practice What if you had function support?

Before you try to add WhatIf support to your scripts, it’s important to understand that there’s a correct and wrong method to accomplish it. You’ll find out what they are in the next sections.

Making a Mistake: Don’t Re-invent the Wheel

It’s fairly commonplace for script developers to provide their own WhatIf support using if/then logic. An example may be seen below.

It’s worth noting that the developer has their own WhatIf switch parameter specified. They then utilized an if/then construct to handle the logic when the WhatIf argument was used or not, based on the value of that parameter.

Remove-LogFile param ([Parameter(Mandatory)]) Remove-LogFile param ([Parameter(Mandatory)]) Remove-LogFile param ([Para [string] if ($WhatIf.IsPresent) ($name, [switch]$WhatIf) # The WhatIf switch is turned on. “WhatIf: I will delete the log file “”$name””” -ForegroundColor Yellow” Write-Host “WhatIf: I will delete the log file “”$name””” -ForegroundColor Yellow” Write-Host “WhatIf: I will delete the log else # What if the switch is turned off? -ForegroundColor Green Write-Host “Delete log file “”$name”””

When the aforementioned function is called with the WhatIf argument, as seen below, it seems to have completed its task. The method returned a message to the console instead of actually removing anything.

PS51> Remove-LogFile -name log.txt -WhatIfPS51> Remove-LogFile -name log.txt -WhatIf

What’s wrong with this technique if it works? Because you’re overlooking an advanced function’s built-in capabilities. Instead of concentrating on what the command will do when it is turned off, you should embed this functionality into every function you construct.

Instead, use the SupportsShouldProcess keyword in conjunction with the $PSCmdlet to avoid reinventing the wheel. ShouldProcess(). That’ll be coming up soon.

Using SupportsShouldProcess Correctly

The [CmdletBinding()] keyword makes all functions “advanced.” This keyword enhances the function’s capabilities, including support for WhatIf scenarios.

All advanced features have WhatIf capabilities; nevertheless, it is up to you to use it. To do so, use the SupportsShouldProcess keyword first, in between the [CmdletBinding()] parentheses, as seen below.

[CmdletBinding(SupportsShouldProcess)]

The function now enables you to check if the WhatIf argument was supplied to the function by using the ShouldProcess() method on the $PSCmdlet function variable. ShouldProcess() returns False when the WhatIf argument is utilized. It will always return True if none of the other conditions are met.

[cmdletbinding(SupportsShouldProcess)] Remove-LogFile function param ([Mandatory Parameter)]) ($PSCmdlet.ShouldProcess($name)) if ($PSCmdlet.ShouldProcess($name)) ## The -WhatIf argument was not utilized in this example. The function should work as expected. -ForegroundColor Green -Host (“Delete log file” + $name) else ## The -WhatIf option was used. The function should not be executed.

WHAT IF A PARAMETER WAS APPLIED? RESULT OF SHOULDPROCESS()
True False
False True

As you can see, when Remove-LogFile is run with the WhatIf option, it behaves just like the built-in cmdlets.

PS51> Remove-LogFile -name log.txt -WhatIfPS51> Remove-LogFile -name log.txt -WhatIf

Summary

You learnt about the PowerShell WhatIf parameter in this post. You should now have a better understanding of how it works and the advantages it may provide.

You should also remember not to recreate the wheel the next time you need a PowerShell failsafe. Instead, make use of the current PowerShell WhatIf functionality!

Additional Reading

The “start-process whatif” is a PowerShell command that allows users to run commands with the WhatIf parameter. The WhatIf parameter will allow you to see what would happen if the command was run without actually running it.

Frequently Asked Questions

What is the WhatIf in PowerShell?

A: WhatIf is a function in PowerShell that checks the output of other commands.

When using a cmdlet help file the WhatIf option may be used what is the WhatIf option?

What is confirm and WhatIf in PowerShell?

A: Confirm is used to check if a command or parameter was received as expected. For example, when you want to test that you have the right parameters for a script and then run it to see its output, confirm could be called before running the script. WhatIf allows users to monitor scripts without actually executing them so they can compare their results with what would happen if they ran the code in question but instead of actually committing those changes, it just prints out messages about how much time will pass until each change takes place (not counting any pauses) or whether its going ahead with actual execution.

Related Tags

  • the -whatif and -confirm parameters are not supported for script blocks
  • if – powershell
  • exchange powershell whatif
  • azuread powershell whatif
  • invoke-command whatif