Tags


powershell

So we’re now looking at Powershell and realizing it’s a whole lot more than a big funky Blue command prompt.   Even if it just appears that way to make us more comfortable.

So one of the nicest things I ever got out of Powershell (the thing that just HOOKED me in) was the easy way it could work with files and folders.

For example GET-CHILDITEM (when working in the default context of the File system) gives us our familiar Directory and files.

But what we’re REALLY getting is a list of Objects and that list can be accessed item by item, just as if you were going and view rows and columns in an Excel Spreadsheet.

So here, let’s get a directory with some files and folders and store them away for safekeeping.

$LISTOFSTUFF=GET-CHILDITEM C:\Scripting

So if we were to try accessing this information in $LISTOFSTUFF we can just key in

$LISTOFSTUFF

which will dump the whole pile on our screen. Or we can examine it Piece by Piece like this

$LISTOFSTUFF[0]

$LISTOFSTUFF[1]

$LISTOFSTUFF[2]

…… etc etc etc…

But wait! There’s more! I can tell you how much “Stuff” is in $LISTOFSTUFF

$LISTOFSTUFF.Count

But the magic isn’t over.   Have you EVER wanted to find all .TMP files on a file system?  or any other type?

GET-CHILDITEM –recurse –include *.tmp

One line.   and again you could store that away in a variable to work with it more easily

$TEMPORARYJUNK=GET-CHILDITEM –recurse –include *.tmp

But here is where the fun starts.  Do you remember how we can compare dates and times?  How would you like an EASY way to show all files that have been accessed in a certain time range?

With each of the items in the directory there is a field called “LastWriteTime”.  This field has a Date and Time you can use to compare with.  But how does one does this?

Remember Piping?  We can run that list of information into another Cmdlet called “WHERE-OBJECT”.  WHERE-OBJECT has a very simple job and that is to Look at information given to it and filter based upon criteria.

In English? It lets you pull what YOU want out of a list.

To to figure out if a file is a certain “age”, just Subtract the “LastWriteTime” with the “CurrentTime” (GET-DATE)

Why?  Well think about it.  Every file is automatically going to be (well just ABOUT every file) older than that EXACT point in time you did “GET-DATE”.

So you could get the date

$STARTDAY=GET-DATE

and then GET the Directory and files like this

GET-CHILDITEM C:\Scripting | Where-Object { ( $STARTDAY-$_.LastWriteTime).Days() –gt 3 }

Will show you all the files in that folder over 3 days old.

And just as easily you can tell it with one minor change, all the files that were accessed within the past hour

GET-CHILDITEM C:\Scripting | Where-Object { ( $STARTDAY-$_.LastWriteTime).Hours() –lt 1 }

Have I poked at your Curiosity?  Good.  Next time we’ll show you how easy it is (and safe) in Powershell

The Power of Shell is in YOU

Sean
the Energized Tech

Advertisements