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")
2. Double Pipe Line '||' to execute a 2nd command if the first failed
(Ex: Test-Connection google.ca -Count 1 || Write-Host "No internet?")
3. 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
2
u/dodexahedron Jan 22 '26
The only $variables that evaluate to $false in a boolean expression in powershell are those which are nonexistent, explicitly $false, 0, $null, have the true and false operators or implicit boolean cast operators in their type definitions, or those that have an explicitly defined conversion in the language that yields $false for the value (notably, an empty string or an empty collection are common ones there).
You can certainly be more explicit and expressive of intent by doing a Get-Variable and checking the result of that, and sometimes that is the right thing to do or just a matter of style. But if it isn't necessary to be that precise and you either have a type guarantee or otherwise can safely trust the equivalent truth or falsehood of the variable, it is fine to just use it naked in the
if.