PowerShell 7 Ternary Operator

by Dec 2, 2019

With PowerShell 7, the language gets a new operator that created a lot of debate. Basically, you don’t have to use it, but users with a developer background will welcome it.

Until now, to create a condition you’d always have to write a whole lot of code. For example, to find out whether your script runs in a 32-bit or 64-bit environment, you could query the length of a pointer like this:

[IntPtr]::Size -eq 8) 
{
    '64-bit'
}
else
{
    '32-bit'
} 

The ternary operator makes this a lot shorter:

[IntPtr]::Size -eq 8 ? '64-bit' : '32-bit' 

In essence, the ternary operator (“?”) is a shortcut for standard “if” conditions. It works on any expression that evaluates to $true or $false. If the expression is $true, the expression after “?” executes. If it is $false, the expression after “:” executes.

If you have installed a PowerShell 7 preview, make sure you update to the latest version to be able to use the ternary operator. It was not part of the initial PowerShell 7 preview.


You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: https://psconf.eu (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: https://psconf.eu/register.html. Help build the agenda and make this “your” event by submitting hypothetical sessions you’d like to hear: https://powershell.one/psconfeu/psconf.eu-2020/reverse-cfp. And if you’d like to present yourself and join the psconf.eu speakers’ team, submit proposals: https://sessionize.com/psconfeu/.

Twitter This Tip! ReTweet this Tip!