Foreach loops in PowerShell, how to use them and which one to use when

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in powershell there's actually four different ways of doing four inch loops or three depending on how you look at it there's four inch four each four each and of course for each object so in this video i wanted to loop through how to use each of them what the main differences are and later on i'll also show you that one of them is significantly better performing than the others and one or two of them is significantly worse performing than the others i'll also loop through use cases for each of the different ways because which loop you should be using is not always a matter of personal preference sound good let's loop if you're not familiar with for each or loops at all here's a brief explanation a loop is in its basics just do something over and over each time you do that something that's called an iteration and you can have different kinds of loops there could be a loop for x amount of times loop until something happens or changes loop until i stop you or as we'll be covering in this video i have a bunch of stuff here loop once for each one of them and this is pretty much true for every scripting or programming language they all have their ways of doing loops but those basic types of loops is something that most languages have all right now to powershell and forage loops like i mentioned in the intro you have four ways of doing 4-h loops in powershell so let's introduce our contestants you have the statement the method the alias and the commandlet let's first look at the one that has been my favorite for years the statement a friend and colleague of mine likes to call this one the real forage loop and that's partly because this way of doing for each loops is what most closely resembles how you do forage loops in other languages if you're used to doing loops in for example php or c-sharp then this way of doing 4-h loops will look quite familiar so let's take a look at how one uses the for each statement all right so i've prepared some lines of code here and first we need something to loop through so let's just grab a few numbers and some services so i'll just run that and here we have the for each statement it starts with a new line beginning with for each then you have a parenthesis where you start by declaring a variable which you'll reference throughout your loop and then you define what you are wanting to loop through in this case it will be a few numbers meaning the numbers 1 through 1337. after that parenthesis you have a curly bracket and this just indicates that now the scripting begins this is where you put your script back and in my case here i'll just grab the type of number say if you look here we reference the number variable that we define here then we simply run the get type method on that number so if i now run this piece of code that should return the type for that number and as you can see they all are all integers so that's a simple one and let's grab another example so next one here is for each service in services so this first one is a variable we defined and the second one is just a reference to what you want to loop through in our case now that would be get service or rather the results of get service and then we do some things for each one of these in this case i'll just i've just used stop service so as an example another way you can do the for each statement is to first again begin with 4-h define a variable that you want to use and reference in your script block and now instead of referencing a variable we actually run some code to get the stuff that we want to loop through in this case i'll you to use get process to list all the processes on my computer and then that's what we're going to loop through so again this would then stop each and every process found in the get process quant all right next up is the method and this one is actually the newest one of our contestants if my memory serves me correct it was only added back in the powershell version 4. and as you might guess this way of doing for each loops is a method meaning that the object data array call it what you want that you want to loop through might have this method built in the method way of doing for each loops is according to documentation and a lot of blog posts faster than both the for each statement and the for each object commandlet later on in this video i'll show you why that's um how should i put this true so let's check out the usage of the for each method all right so the same kind of preparations here i first define what i want to loop through and then i have an example here of using the method you see we reference the a few numbers variable um this object contains a method called for each so basically i'm calling the method contain in the object a few numbers and that method is called for each and then i have parentheses and then within these curly brackets here that's my script bug so that would then be the same as the contents of the curly brackets from the statement example and running this piece of code here should provide us with the exact same result as the example we used with the forage statement so let's just try that and we see that it's pretty much the same thing what we get back is the type of each and every row or thing in that a few objects main difference that you might see here is that now we instead of defining a variable that we reference in our script pack we simply use the dollar underscore and this is exactly the same as we'll see later on when i show you the for each object commandlet and by having to reference the dollar underscore instead of some variable that we defined you lose a little bit of readability but that's a preference kind of thing and this is the first example here is split across multiple lines for readability but you can use it like this one here where we spell it out on one line in the entire thing the same thing goes we reference our object which contains the for each method and then some parentheses and curly brackets and then what we want to do with all the stuff in the services object in this case stopping each and every service and again here we can also run lines of code instead of referencing an object so i could do a get process here and then reference the method for each same kind of thing but the cool thing about the for each method is that it can actually also call or invoke methods of each and every line in the object so for example if i do it like this i do i get process meaning i'm grabbing all the processes on my computer and for each of them i'm referencing this method which is in fact a method on each process and this will effectively just kill each and every process on my computer and same as the example before with the stop process now one thing that is true for all kinds of for each loops is that you don't actually have to do something with the object you're referring to so i just want to show an example here where i still i use the get process and for each meaning i call the method for each of the object i will do write host hi meaning that for each of every process found on my computer this should now output hi in the terminal so let's see how that would look pretty simple huh so with each and every one of these for each loops you don't have to do something with the object but you can do something based on the number of processes for example right that's the for each method the next stop is you know actually the last two of our contestants the alias and the commandments i'll cover them at the same time and that's just because the alias is well it's an alias for for each object meaning they are in fact the same i must admit that i really don't see why the four-ish alice needs to be there in the first place as it's only providing confusion and room for misunderstanding if you put 4-h at the start of a line it's a statement if you put 4-h as a part of the pipeline it's an alias easy right anyway the for each object commandlet is often the first for each loop you learn about when you're starting out your powershell journey at least it was for me back in the days and i was using this way of doing 4h loops for years up until i was introduced to the 4-h statement the 4-h object commandlet and its alias is a very powerful way of doing things so let's jump back into visual studio code and some examples on it by the way all the code used in this video will be up on my github link down in the description and while you're down there hit that like button and subscribe button as well as it helps out a ton i hear all right so first up the alias as you can see here we have still have our a few numbers and then we pipe it you know because we're doing the pipeline thing two for each and as you can see in visual studio code this actually gives me that yellow squiggly line because forage is an alias of for each object and you should not use aliases at least not in your scripts but anyway we have our object we pipe it to four each and then we have the curly brackets which contains our little code snippet so this little piece of code should produce the same result as we saw in the previous examples as well so let's just run that and we see that well all the numbers are still integers so that's fine i guess you can also see that here we have the same kind of referencing as you saw with the for each method meaning you only use the dollar underscore to reference whatever you're looking through another way of doing it is of course on one line you lose a bit of readability but produce the same result and likewise you could loop through for example each service do a forage and stop them all again referencing with the dollar underscore or you could run some lines of code pipe it on through to the for each and then do something with it in this case i'll get all processes on my computer and then pipe it to the for each alias and then use stop process on each one of them and that's the alias if we take a look at the commanded this is exactly the same as with the alias you're just providing a bit more readability so that's how you use the different kinds of for each loops i would now like to do some measurements to see how they perform as i mentioned in the intro some of these methods or ways of doing forage loops perform differently than the others so i have prepared some measurements here so in this case we need a bit something a bit larger to loop through so we will grab a lot of numbers and then i have multiple lines here this basically does the same kind of loops that we saw earlier for example grab grabbing the type of each and every number but in order to find out just how long each and every run takes i'll use the measure command and then i'll pipe that on through to select object so that i only receive the total seconds so i'll run each of this five times and then you will see the results in the end and through the magic of editing i'll be back once this is all finished finally done and now that we have the results we can see that the commandlet used around 45 seconds each run while the alias let me see the alias you also used around 45 seconds which is exactly as expected seeing as they are the same and let's see the the method they used around 33 seconds so that's a major improvement but if we check out the statement oops the statement only used around 7 seconds that means that this statement at least in this kind of scenario is the by far fastest way or the best performing way of doing 4-h loops all right so now that you know how to use each way of doing 4-h loops and a little bit about the performance i guess you want the answer to the big question which one should i use and i'm sad to say that the answer is as with a lot of other things it depends each way of doing 4-h groups has their use cases and advantages except for the alias of course you should never use that so let's consider the usage of each way starting with the statement the 4-h statement should pretty much be your go-to way of doing 4-h loops i would recommend using this way unless there's some specific feature of one of the other ways of doing for each clips that you need for example if you need to use for each as part of the pipeline the forage statement is simple it provides a good level of readability and since it loads everything in ram before starting the first iteration it is usually blazingly fast compared to the other ways of doing forage loops the 4-h method however is more like a swiss army knife since it can be used to invoke the methods of each object it's it also provides a lot of potential functionality it can be a bit lackluster in the readability section but definitely has good use cases performance wise the method is a bit slower than a statement but that's only if you use it as a simple forage loop if you for example use the for each method to loop through and call methods of the things you're looking through that's where the 4h method shines and where it actually outperforms all the other ways of doing for each loops let me show you what i mean so down here in my measurement script i have where the method shines so in order for this example to really work we need something that has a method built into it so we need some processes so let's start by starting up 100 notepads like so uh if you just wait a few minutes they are opening up here on the other screen all right now i should have just about a hundred notepad uh processes going now i could go ahead and kill them with a statement meaning i use for each and then for each process in the get process with the name notepad i should stop the process so this is quite simple i can just select this run it and all my hundred notepad processes is gone but let's open them up again right i have a hundred notepad processes again now let's kill them with the method because the get process has a method called for each and each and every process has a method called kill so that means i can select all this and just hit run on them and they're gone so that's pretty easy way of using the forage method to call a method within that again but just for fun uh let's do the same with the commander right i have another hundred processes of notepad the commanded way of doing it would be the get process name notepad and then pipe it to for each object and then start process so let's select that and run and there you go so you can use all kinds of forage loops to actually kill all these processes but let's do some new measurements now that we are using the for each method to call another method so once again fire up 100 notepads right i have a 100 notepads uh let's measure how long this takes with the statement so i'll just select this and run it right that took a total of 0.8 seconds as you can see here now let me just fire up a hundred more right 100 notepad processes going so let's use the forage method to kill them and measure how long that takes that took a total of 0.03 seconds just for fun we're going to do the same with the commandlet so let's fire up notepads again a hundred ones right i have a hundred of them let's use the commander to kill them all and that took point seven nine seconds which is just about the same as we saw but the statement but again the for each method used what was it point zero something point zero three seconds that's a whole lot faster so this is a kind of use case where the for each method really shines and we've covered the statement and the method so let's look at all the use cases and advantage of the alias all right that covered let's jump to the last of our contestants the commandland like i mentioned earlier this was the first kind of forage loop i learned in powershell and i used it for years all until i was introduced to the statement way of doing 4-h loops which made me switch completely because suddenly the command was so slow and the command is slow compared to the statement mainly because while the statement loads everything in ram and runs it from there the commandlet runs each and every iteration from the pipeline that does have an advantage though if you're low on ram the commandlet does have its advantages and use cases though it is more feature packed than the statement although not as much as the method an example of this is that the for each object's commandlet it supports the use of begin process and end which you might be familiar with if you've ever created advanced functions in powershell which maybe is a topic i should cover let me know in the comments if that's something you want to see so to sum up this section of the video use the for each statement as your default for each loop use the forage method if you need advanced features like calling other methods never use the alias use the 4h object commandlet if you're low on ram or need advanced features like begin process and end also the commandlet is useful if you need to use the pipeline like i mentioned before each statement will break the pipeline while the commander will let you continue it now that you know all about forage loops it's time to combine them with vert progress so you can get those sweet progress bars learn all about that in this video and with that thanks for watching like and subscribe to the channel and uh yeah see ya
Info
Channel: PetterTech
Views: 3,175
Rating: undefined out of 5
Keywords: powershell, foreach, powershell tutorial, powershell basics, powershell scripting, scripting, powershell foreach, foreach loop, automation, learn powershell, powershell training, powershell scripting tutorial, for each loop, powershell scripting for beginners, powershell for beginners, foreach-object, powershell loops, windows powershell, powershell tutorials, getting started with powershell, powershell intro, learning powershell, powershell examples, powershell explained
Id: I_V31oh5iYU
Channel Id: undefined
Length: 20min 43sec (1243 seconds)
Published: Fri Jun 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.