So last time we were introduced to piping.  A more efficient way to port results to different programs.

Now in Powershell we have to remember the information we’re dealing with is OBJECTS.  It’s important to remember that what you see on the screen, although VISUALLY text, may not be.

Think of those Objects much like a spreadsheet.   It’s a list. It’s a SPECIAL kind of list, but on a very basic level; it’s a list.

We may just want to GET the ITEMS from the list and just see them.  (GET-CHILDITEM) or we may want to examine them a little deeper.

This time, we may want to look at the Objects individually.  Perhaps examine them a bit more deeply.   The simplest way is with the “FOREACH-OBJECT” statement

With the FOREACH-OBJECT statement we have a special builtin variable.   You’ll notice variables in Powershell (Items containing information) represented by a “$”.  In the case of the Foreach-Object statement there is a variable called “$-” which represents whatever OBJECT we’re presently looking at.

So here’s a simple example with our “GET-CHILDITEM”



Which really isn’t very impressive right now.  All we did was get a list of objects and say “FOREACH-OBJECT” “Echo” $- (That Object)

But here is where the Powershell starts to open up

That SAME line with a little change can access SPECIFIC information from those objects

GET-CHILDITEM | FOREACH-OBJECT { $-.Name, $-LastAccessTime }


What that is doing is going sequentially though the list of objects and pulling out SPECIFICALLY the Name Property and LastAccessTime Property from the output (Remember that information provided with the GET-MEMBER ?)

You can even assign the results of that to a Variable for later use and manipulate it however you want

But here’s a better example of the FOREACH-OBJECT in Action.  To see how I can manipulate the results and maybe do something with it later afterwards.

Let’s take a look at this line



So that just pulled up a list and showed me all the time those Objects were last written to

Then this system we’re going to apply a METHOD to those Objects (As shown from running a GET-CHILDITEM | FOREACH-OBJECT { $-.LastAccessTime } | GET-MEMBER )


We’re going to use the “AddHours()” Method on the “LastWriteTime” Property


GET-CHILDITEM | FOREACH-OBJECT { $-.LastWriteTime.AddHours(96) }


What did I just do? 

I pulled up a list of OBJECTS with GET-CHILDITEM.  I ran the results through a FOREACH-OBJECT and ran a Method against “EACH” object given (supplied by our friend GET-MEMBER which said which Members and Properties we could use) and said in this case “Add 96 Hours to value of that Date Object”.   This DOESN’T write back to the original item but it IS a way to manipulate information.

Still in just one line.  We’re working with the Structure of an ENTIRE file system in One line and dumping a list to the console with EVERY date Modified to work with.

And what we’ll do with that information, we’ll touch on next time.

The Energized Tech