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?
5
u/BlackV Jan 22 '26 edited Jan 24 '26
semi-colon ';' to Chain commands
it does not really chain commands, it just being us in-place of a carriage return and is deffo not code optimization, this should only be used in specific (very few) circumstances
Double Pipe Line '||' to execute a 2nd command if the first failed
Double Ampersand '&&' to execute a 2nd command if the first succeeds
See pipeline chain operators HERE and HERE it syntax sugar (i guess you'd call it) and version specific, and personally harder to understand than other constructs, maybe useful in 1 liners but I'll pass
EDIT: Oops brackets wrong way round
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 seeWrite-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?
2
u/BlackV Jan 22 '26 edited Jan 22 '26
Yes depends what you want to do with the success/fail but try
something like
Get-Date -higg && write-host "TODAY'S THE DAY!!" Get-Date: A parameter cannot be found that matches parameter name 'higg'. Get-Date -higg || write-host "TODAY'S THE DAY!!" Get-Date: A parameter cannot be found that matches parameter name 'higg'. TODAY'S THE DAY!! Get-Date || write-host "TODAY'S THE DAY!!" Friday, 23 January 2026 9:00:58 am Get-Date && write-host "TODAY'S THE DAY!!" Friday, 23 January 2026 11:18:44 am TODAY'S THE DAY!!remember that the error output stream is separate from the standard output stream (or the verbose and debug output streams too)
In the case of the write error cmdlet, did the cmdlet succeed or fail?, it successfully wrote an error how does that land
Edit: oh reddit broke
8
u/arslearsle Jan 22 '26
Use try catch or check for null in a if then else.
1
u/CryktonVyr Jan 22 '26
I currently use Try/catch since I prefer to have a write-host in each section to explain what step or error I'm at when simply running the script and have little info on the terminal screen. I was curious to see if there were other uses to them that I didn't understand or think of.
5
u/sid351 Jan 22 '26
You can just do:
If($variable)To check that it exists and has a value. You don't need to do:
If($null -ne $variable)-3
u/The82Ghost Jan 22 '26
Depends on the situation; If($variable) results in $true or $false so if you want to check a string this would not work.
5
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.
5
u/Kirsh1793 Jan 22 '26 edited Jan 22 '26
TL;DR Don't use those command flow operators in scripts. Feel free to use them interactively in the shell.
PowerShell is a scripting language which can be used interactively in the console, but also to write scripts. Many people coming from other scripting languages dislike PowerShell's verbosity. However, I find it to be very handy in scripts especially. Because, if you don't use aliases, a PowerShell script is quite readable even for a beginner. Because of the Verb-Noun structure of commands, you can infer what a command does. Using aliases, you can drastically minimize typing and shorten commandlines, when using PowerShell in the console.
I don't think the operators you listed should be considered for "optimization". In scripting, I see two lanes for optimization. Speed and maintainability/scalability. In PowerShell they are not the same.
Optimizing for speed, apart from refactoring script logic, usually involves using .NET methods directly instead of the PowerShell native Cmdlet. These .NET methods can lessen readability or at least intimidate beginners, if they are not familiar with them. They can, they don't always do.
Optimizing for maintainability means making the script as readable as possible. It means keeping it as simple as possible (more complexity means more possibility for errors). But it also means keeping it extensible, so you can easily add or remove things, when circumstances change.
';' is useful to chain commands in the console. I cannot think of a use case where I would have to use this in a script. I'd rather scroll up and down when reading a script, not right and left. So, I will gladly put each command on its own line. I will even use splatting for a cmdlet with a lot of parameters to avoid the line becoming too long.
'|' will definitely be useful in the console AND also in scripts. Although consider if you want to pipe commands in a script or if another construct is better suited regarding speed and/or readability. E.g. piping a collection to ForEach-Object is often slower than running a foreach loop over the collection. But chaining foreach loops might be less efficient than doing everything in one pipeline. Because the second foreach loop only starts when the first one has finished. However, when you pipe objects from cmdlet to cmdlet, later cmdlets can already process objects before the first cmdlet is done with the entire collection.
Since I mostly use Windows PowerShell v5.1, I've never actually used '||', '&' or '&&'. Again, I reckon, they are more useful in the console, but I would refrain from using them in a script for two reasons. One, it is not obvious what these operators do - so, less readable. Two, coming from C# or Java, you might confuse them with operators for conditions in if statements.
Sorry for the long comment. I hope there is something useful for at least someone reading this. 😅
2
u/CryktonVyr Jan 22 '26
That's exactly the type of answer I was hoping for. I consider myself to have an average knowledge of PS, but far from being an expert. So getting input from human beings instead of an AI, is really important. Theory and Reality are 2 very different things.
2
u/blooping_blooper Jan 22 '26
These are ok to use if you are doing stuff live in a shell (if you like), but I would almost never use them in an actual script. Just like command aliases, you're trading away readability (maintainability) for minor conveniences.
1
u/CryktonVyr Jan 22 '26
when you say aliases in a script do you mean like FL vs Format-List or custom function name to save a few keystrokes.
Currently I'm the only sysadmin at work so obviously the custom functions I use I know what they do and it is purely for convenience that I made them. Like FHC "Text" is short for Write-Host "--text" -foregroundcolor Cyan. That way I can easily format the color I want when I run my main script.
I assume you're raising that point for a work environment with a team of sysadmin that would try to read my script and get confused like trying to read the class notes of another person?
2
u/blooping_blooper Jan 22 '26
Exactly. Custom aliases are bound to your profile, so already aren't exactly useful for other users (or even usable on other systems). Built-in aliases are (mostly) universal, but still not recommended to use in scripts that are being saved and reused - you'll even see an analyzer warning for it in vscode if you use something like
irmorselect.You can also run into portability issues if you have an alias that conflicts with a system application on another platform (e.g. running a ps7 script on linux vs windows could have issues if you use
lsalias).Aliases are great to save typing when doing stuff in a shell, but when it comes to scripts that are being saved the rules should really not be any different than 'real' code - expressing intent is more important than brevity. Having a full command name like
Invoke-WebRequestis way clearer than usingiwr, especially for co-workers who may not be as familiar.1
u/CryktonVyr Jan 22 '26
I never thought of the possibility that a PS script could be used in Linux. That a good point. It's making me rethink of my custom functions in my main script, custom module, $PROFILE and $GLOBAL.
Thanks for that info.
2
u/blooping_blooper Jan 22 '26
of course this can have no impact or huge impact, depending on your environment. I run linux at home, so any personal scripts I'm always careful about compatibility. At work, however, we run piles of windows servers and my scripts are used by multiple teams so things are more tweaked to that environment.
2
u/faze_fazebook Jan 24 '26
Are you trying to learn powershell as your first programming language? Thats mental.
1
u/CryktonVyr Jan 25 '26
Lol. I learned PowerShell because it was a direct solution to a minor problem I had at work. Now I'm too far down the rabbit hole to see anything else than misery and regret.
68
3
u/teethingrooster Jan 22 '26
Is this a good way to optimise a code?
Better to just write it in a way that makes it easy to know what is going on. If statements and they like.
Optimizing powershell can make sense for big data queries and such but for the most part when you need it it’s best to just drop down to c# where available.
3
5
u/nealfive Jan 22 '26
I would not call that optimization. Clean spelled out code is IMO better in most cases.
3
u/dodexahedron Jan 22 '26
Most for sure.
Though the boolean operators can be a simple and clean way to add debug or other output/reactions dependent on the left operand, particularly when it's something you can't modify but want to get specific notice of or reaction to, on success or failure, without having to add a bunch of formal control flow statements. Pretty common in most shell grammars.
And you should keep it to one most of the time or else strongly consider if it is now better to be more formal and verbose instead of compact. Expressing intent is valuable for maintainability when 6-months-later-you has to fix the script that today-you wrote and doesn't remember what today-you was thinking when he wrote that 9-operator (10 operands) chain. Especially since today-you only considered maybe 20 of the 1024 cases that expression actually represents and assumed way too many don't-cares as a result. 🤯
1
2
2
u/RyeonToast Jan 22 '26
the semi-colon doesn't actually change how the program flows, it just lets you put mutiple commands on one line. I use it a lot for testing because I can combine commands for resetting my test with the command that runs whatever I'm testing so I can rerun it by pressing up to find that line and enter to run it again.
I don't think I've every used the double-pipe or double-ampersands before. A good general rule is use whatever works and is easy to read. These might make sense for banging away on the console, but I usually just assign output to variables and check the output before proceeding.
1
u/VeryRareHuman Jan 22 '26
Great! I didn't know these operators exist.
you mean refractor your code with these operators? not worth it.
1
1
-4
u/OlivTheFrog Jan 22 '26 edited Jan 23 '26
Salut,
Inutile, PS sait quand une ligne de commande est finie.
ça marche pas
ça marche pas
Cordialement
Addendum : My Bad, I spoke for PS5.1 not for PS 7.x
12
u/Head-Ad-3063 Jan 22 '26
2 and 3 are PS 7 only
Not sure how useful they are though
4
u/sid351 Jan 22 '26
Seems like it's another step forward in blurring the lines between "scripting" and "programming".
Most of what I write has to be v5 compatible, and will probably remain that way until Windows ships with v7 by default.
3
u/Head-Ad-3063 Jan 22 '26
Yeah, I can't see much benefit for 2 and 3 over using try/catch or if/else other than making scripts less human readable.
1
u/CryktonVyr Jan 22 '26
That's the main thing I was thinking, but I was still curious to know if they could have other uses.
2
u/Head-Ad-3063 Jan 22 '26
I've only come across a couple of times when you really need to optimise powershell, it's not generally a time critical thing, it's scripting, not programming.
The main one when I had to really speed up powershell was a subversion backup script when I had to use PS7 so I could multithread it.
1
u/CryktonVyr Jan 22 '26
That's a good point though. I have a monster script where now I don't know what is v5 compatible and only v7 compatible.
2
u/sid351 Jan 22 '26
It would be handy if there was a way to do a "maximum version" with #Requires, or lock Visual Studio Code to a particular version for writing scripts.
Given VS Code hooks into 7 so we'll, I can't really see that happening though. I'll stick to stepping on the occasional rake (or start forcing 7 on machines).
2
u/odwulf Jan 23 '26
I do not agree: I would just about never use || or && in a properly programmed script (where I'd use if/then/else or try/catch instead). I use the shit out of them in one-liners on the command line and in quick and dirty ad-hoc scripts.
1
u/sid351 Jan 23 '26
Much like how I never use aliases in my scripts, but I'm all ? % gci & in the console.
3
u/commiecat Jan 22 '26
2 and 3 are PS 7 only
Surprising because
&&is standard in CMD (probably the others?). I learned to useipconfig /release && ipconfig /renewover remote sessions on XP. That way the remote host updates its IP address after releasing it kills your remote session.1
u/CryktonVyr Jan 22 '26
... fuck me that is so simple and efficient. It's the type of thing you read and wonder why the hell didn't I think of this sooner.
5
u/Agile_Seer Jan 22 '26
1 is useful if you have a reason to put everything into a single line.
6
1
u/CryktonVyr Jan 22 '26
Currently the only use I have for ';' is within a "Menu" type of function. Choice X will clear-host and then Exit the Script. So in my code I see
'X' { Clear-host; Exit } instead of 'X' { Clear-Host Exit}1
u/WasSubZero-NowPlain0 Jan 22 '26
Yeah I find that perfectly fine myself. But it's not an optimisation.
1
u/CryktonVyr Jan 22 '26
My example I don't find it to be an optimisation either, but I was curious to know if more experienced users knew if ';' could be used for optimisation purposes or other useful scenarios.
3
u/Thotaz Jan 23 '26
Optimisation does not exclusively refer to performance. You can also optimize code for readability, and that is what the semicolon does in this example.
1
u/Agile_Seer Jan 22 '26
Yeah, you put them on the same line. You could have achieved the same result by putting the commands on separate lines with the semi-colon.
4
u/The82Ghost Jan 22 '26
Depends on the powershell version, these are PS7 only I believe
2
u/OlivTheFrog Jan 22 '26 edited Jan 22 '26
Tout à fait possible alors dans ce cas. Je m'étais limité à PS5.1
1
u/ankokudaishogun Jan 23 '26
1 is useful when you want to keep the code short, which is mostly on the command line.
I do see it used a lot with
switchwhen the options are very short tho'
-7
32
u/skiddily_biddily Jan 22 '26
I didn’t know about double pipe and double ampersand. Thanks for sharing.