Pages

Monday, December 9, 2013

Looping, making your scripts useful

Ah, looping. You either think this is the easiest thing on earth or, you told your boss something like this about 20 minutes ago "Yeah, we can get a script to do that, like, maybe through a list or something." Luckily creating loops in Powershell is very simple, with a few ways you can do it, but they all essentially do the same thing. Which is stuff. Repeatedley. If you read any of my previous articles, you might have noticed the one about Do and While loops. This is actually a loop as well, though not necessarily in the typical sense that most people use them for.

I'm feeling less verbose than usual today, so let's get this party started.

Pancake:
foreach ($item in $var)
    {
    #Process stuff
    }

So there we go. That's your first loop. For most people, you're going to want to be reading stuff from a list and performing some tasks based off of that. So if we wanted to grab stuff from a .txt file, then we could make a script similiar to the one below.

$ComputerList = Get-Content "C:\Working\computerlist.txt"

foreach ($Computer in $ComputerList)
    {
    Write-Host $Computer
    }

So what happened here? First we used Get-Content. Get-Content is used for many things, but usually it is for opening the content of a file. In this case we are using a list of computers. When you create a list in a text file, each line is a new object, for as many lines as there are. Do note if you have empty lines entered (let's say perhaps with nothing but spaces) then you will get some garbage in your script. As far as Get-Content is concerned, those white spaces are indeed content.

Once we got the content of that text file inside of our $ComputerList variable, we created a variable foreach item in that list. Starting from top to bottom, one line at a time. We can name this variable whatever we want, in my example, we named it $Computer. Because that just makes sense. You can name it $Pancakes (preferred), $Pretzels, whatever you want really. After that we open a scriptblock { }, and inside of that script block we can do whatever our hearts desire. You can nest as many foreach loops as you can logically stand (I get really confused after I start heavy-nesting), use if/else statements, anything you want essentially. Just think of it as another little script, except only for that item that you specified. It will run through the scriptblock, and then do it again for the next item in your list, until your list is exhausted. Once your list is exhausted, it will exit the loop and continue processing the rest of the script, if you have anything left to process, that is.

This is it, a short simple sweet (no pun intended) article. Later I will talk about other uses foreach loops, including foreach-object, reading from an array, building arrays, and so much more fun stuff!



No comments: