With PowerShell 7 new operators were introduced. We call them chain operators. Chain operators enables you to do something after doing something. They use the $? and $LASTEXITCODE variable to determine whether a command on the left hand of the pipe failed or succeded.
Let’s cover this topic by demonstrating some examples to fully understand the new pipeline technology.
Open PowerShell 7. Make sure you are actually running PowerShell 7 or higher by checking the version with $PSVersionTable.
The && operator executes the command to the right side of the pipe only if the first command was successful.
Take a look at the examples below to understand whats’s going on.
In the first command (Line 1) the requested folder is not present, therefore the string ‘Not there’ is not executed. We just see an empty output. However, in the second comand (Line 2) the file commands.xlsx exists, therefore the string ‘C:\Temp\commands.xlsx is here!’ is executed and shows up.
Which brings me to the second pipeline chain operator.
The || operator executes the command to the right side of the pipe only if the first command was unsuccessful. So it’s the opposite of the previous one.
Let’s examine this with an example.
The folder in the first command (Line 9) is not present. Therefore ‘Not there’ is executed. What is going on in the second command (Line 11)? Since I have no open notepad process, notepad will be started, because as we have learned, if the first command is unsuccessful, the second command will be executed which results in opening notepad.
The last example shows || in action when the condition is not met, respectively if the first command is successful.
Note, however, that the command on the left side is still executed, which causes the folder structure to be displayed, but the ‘Not there’ string is not executed because the condition is not met (the first command is successful).
That’s it. Hope this was informative and I could demistify theses two new chain operators.