r/PowerShell • u/CryktonVyr • Jan 22 '26
Understanding Optimisation with ';' '|' '||' '&' '&&'
Hello Everyone!
I've been learning to code with powershell on and off for 2 years. I recently learned why using the pipeline '|' helps optimising a script.
I already knew how to use '&' and '|' but I just learned today of the possibilities with ';' '||' '&&' and thought I would share and ask a followup questions to our TEACHER OVERLORDS!!!
- semi-colon ';' to Chain commands
(Ex: Clear-Host; Get-Date; Write-Host "Done")
- Double Pipe Line '||' to execute a 2nd command if the first failed
(Ex: Test-Connection google.ca -Count 1 || Write-Host "No internet?")
- Double Ampersand '&&' to execute a 2nd command if the first succeeds
(Ex: Get-Date && write-host "TODAY'S THE DAY!!")
Now the question I have is. Is this a good way to optimise a code, how and why?
View all comments
Show parent comment
1
u/CryktonVyr Jan 22 '26
That why I asked the question. In the first link you shared I saw a command that in my mind wouldn't work.
Write-Error 'Bad' || Write-Output 'Second'
If you run that on the terminal you should see
Write-Error: Bad
Second
The cmdlet Write-Error 'Bad' succeeded in writing that output on the terminal. So the cmdlet Write-Output 'Second' shouldn't run, but it does. the cmdlet Write-Error 'Text' gets detected as a fail in the eyes of PS so the 2nd cmdlet runs.
The opposite Write-Error 'Bad' && Write-Output 'Second' in my mind would have written in the terminal the second cmdlet since the first one succeeded, but since PS detects it as a fail it doesn't.
Now if you use the Try/Catch method. It follows my thinking. TRY cmdlet write-error 'Bad' if it fails use CATCH cmdlet Write-Output 'Second'. It doesn't fail or detect an error at the TRY section so there's no need to run the CATCH section.
So ultimately it depends on the wanted result or use case or type of logic we have I guess?