Powershell Power! (Part the First)
This will (hopefully) be the first of several ‘tutorials’ on Powershell.
Many of you have probably seen code in the forums or tutorials online that show some exerpts of code that are just CRAZY! Many containing aliases like “%” and “?” and lots of braces and parentheses of all shapes and sizes.
Well, one of the things I love about Powershell is that you can do some VERY powerful, yet hard-to-read things at the command line. While this may seem super and efficient for someone who knows Powershell, it SUCKS if you are trying to learn the language.
When I was trying to pick it up, this is all you could really find and it wasn’t until I found (what I believe to be the Powershell BIBLE) Windows PowerShell in Action by Bruce Payette.
In my mind there are ideally two different styles to Powershell(ing).
- The free-form, Wild-Wild-West, I-need-to-pound-this-out command line style
- The structured, methodical, EXPLICIT scripting style
From a practical sense, though, I think most people end up somewhere in the middle. What absolutely drives me bonkers is obscure-one-liners that veteran Powershell scripters spew to the newbie scripters asking relatively simple questions like:
“How do I get a list of all files in a directory that have been modified in the last 3 weeks?”
One may be inclined to say “Oh, that’s easy! Here it is…”
gci |sort| %{if ($_.LastWriteTime -GT (get-date).Adddays(-21)) ` {write-host $_.name "--" $_.LastWriteTime -foreground Red}}
But for someone unfamiliar with Powershell, it looks like a bunch of gibberish. Now something like THIS may be more helpful for them:
$AllFiles = Get-ChildItem | Sort-Object $Now = Get-Date $CutoffDate = $Now.AddDays(-21) Foreach ($File in $AllFiles) { If ($File.LastWriteTime -gt $CutoffDate) { Write-Host $File.Name "--" $File.LastWriteTime -Foreground Red } }
Okay, if someone is asking this question, they are certainly new to the language and so an obscure response will probably only confuse them and, hopefully, not taint their desire to learn this robust and relatively simple tool.
ANYWAY… sorry about that half rant/half informational bit…Let’s talk a little bit about Powershell…
What *IS* Powershell?
Well the quick-and-dirty is that it is a “new” scripting language and command shell geared for IT administrators with a focus on simplicity, power, and automation.
The “official” description can be found here: http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx
Anyway, now that you have an idea of what Powershell is, we will take a peak at some of the easy stuff you can do with it. I will probably start with some of the fundamentals of scripting and move forward from that.
That’s all for now, but I will write more shortly. I still haven’t figured out what format I want to use, but we will figure it out together.
Thanks for reading, sorry for the mild rant, and happy shelling!
– Mark