Next up is the ternary operator.
This is also something that was introduced in Powershell 7.
This is an alternative to using an if else statement in PowerShell. This
operator is also described in the about_if help topic,
which again, I'm always encouraging you to read the help.
So the way this operator works is like this.
We have some condition to test. That test has to
return a value of true or false.
If the value is true,
then we run whatever code is on the right side of
the question mark. If it's false,
then we run whatever code is on the right side of the colon.
Traditionally, and this is what we would do in Windows PowerShell 5.1,
if 2 is greater than 1, then display yes, else,
display no.
And so we can see yes as the result. And here is the same
expression rewritten using the ternary operator, 2 greater
equal to 1. If that's true, then yes, otherwise, : no,
and you can see the result of yes. So here is a little more complex
example. I'm going to do Get‑Process notepad. Hey,
is Notepad running?
If it is, then I want to stop Notepad, otherwise, I'm going to
write a warning saying Notepad is not running. When you're using
the ternary operator in this regard,
put the expression that you want to evaluate and run in
parentheses. If Notepad is not running, which it isn't in this example here,
then I get my Get‑Process warning and then I get the code that
executes after the colon, in this case, the warning which says
Notepad is not running. Using the ternary operator is great for
really simple if else logic,
especially if you want to do something like this at the
console. When you get to scripting,
my belief, it's just as easy to use an if else statement because
the ternary operator does require PowerShell 7 so you'd have to
take that into account in your scripts, but I don't want to get
too far ahead of us.
Let me show you a few other things here about the
ternary operator. Here is another example,
remember the expression that's on the left side of the question mark has to
be either true or false. $isWindows is another one of these built‑in
variables that is a Boolean value of true or false.
If I'm running PowerShell 7 on Windows, that will have a result of true.
If I'm running this on Linux or Mac, that result will be false.
So if I'm running this on Windows then I can run
Get‑CimInstance, and I'm using the alias gcim, and say hey
get me the win32_operatingsystem w my class.
Otherwise, if I'm not running on Windows, then run a
Linux command, the lsb_release. Now,
I don't know for a fact that will run on all Linux
installs or all non‑Window systems,
but I just want you to kind of get an idea of if I'm running Windows,
then I want to run a Windows‑specific command, otherwise I'm going to run a non‑Windows command.