April 2010 Archives

Powershell

For those of who have been loyally reading the blogs you’ll have been staring at what appeared to be an almost dead page.

Did the world fall apart?   Did Starbucks run out of Coffee?   Did “The Kraken” get tamed?

All valid questions.  Normally I find I blog and twitter like a madman.  As thoughts flow in my head, they get dumped out.  

So what happened?  An amazing and INCREDIBLY cool month!  Of course a busy one to boot at work.

First off, the month started off with a bang, as many of you are aware; I was nominated and received the Microsoft MVP award for Windows Powershell.   That just sent me spinning!  I was floored.  Smiling like and idiot, beaming everywhere at strangers for no reason.

Getting funny looks from my co-workers.

Then of course during the entire month of April was EVENT after EVENT after EVENT!  Energize IT 2010 occured here in Toronto as well as the normal ITPro Toronto meetings.  Tap that into my normal 15 hour day of work and commute and my schedule over floweth!

But then another piece surfaced.  I needed my passport!  A good friend advised me to sort that out since (in his words) “It would be a shame if you had to refuse presenting somewhere really cool just because of that”

Yes, a new passion lit inside of me.  For some silly reason, I now LIKE to present!  Standing in front of a crowd to see if they pull me off the stage.

So my passport needed to be renewed.  Something I haven’t done in … well a long enough time that it was a headache.   It took several booked appointments, finding the right paperwork and isolation from work without my cell phone during that time.

It is done.  Sorted out.  Which means I can now go to the one conference I have been waiting FOREVER to go to.  Microsoft TechEd 2010!  People thought I was “over the top” with Techdays here in Canada?  You’ve not seen nuthin’!

The month of April has quieted down and the following year is about to tear loose :)

So what does this all mean?   The Energized Tech is back and you know what that means.  I’m out, and it’s time to…

“Release the Kraken”

Sean
The Energized Tech

ScriptingGames

April 26th is here and the Scripting Games are back!

Do you feel the power coursing through your keyboard?  The ability to breathe Powershell or vbScript is second nature to you?

Then take up the challenge!  Go today to http://2010sg.poshcode.org and sign up and take the challenges in the 2010 Scripting Games!

Take up the cause and seize the day.  The Scripter is in you!

Sean
The Energized Tech

Powershell

This article was initially intended for Network Administrators.  For a large corporation that wanted to standardize their Powershell setup.

Then I realized others could benefit from this.

If you’re aware of it, in Powershell there is a file based upon your Shell called your Profile.  Powershell ISE has it’s own Profile.

All the profile IS is just a BIG dumb text file you can fill with Powershell commands, functions, settings.  Nothing more than that.

It’s typical location is sitting on %USERPROFILE%\My Documents\WindowsPowershell\ and is usually called Microsoft.Powershell_profile.ps1 or Microsoft.PowershellISE_profile.ps1

And it’s format is just like a PS1 file.  No real difference.   But typically you’ll fill it with functions rather than Executing programs.  But you can use yours however you want.

My task today is to show you how to create a standard profile and pass it along to other administrators.

The easiest way is to just edit your profile the way you want and store is on a network location.  Name it something unique like “OURSTANDARD.PS1”

So “assuming” we have placed the file OURSTANDARD.PS1 on a common share like \\ASERVER\ABADLYNAMEFILESHARE all you need to do is create a NEW shortcut for Powershell launched with the following Parameters in Windows

“%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". ‘\\ASERVER\ABADLYNAMEDFILESHARE\OURSTANDARD.PS1’”

There! You’re done.  You only need deploy a standard Powershell Shortcut to your Network Administrators rather than trying to keep the latest profile passed about. 

And if you’re looking for a Standard Profile to work with?  Here’s something it could look like

----------------- Start Profile Here -------------------------------------

# ABC DEF Ernie Gonzo and Cookie Monster Powershell Corporation
# Commented out so nobody can see this

FUNCTION GLOBAL:GET-PRAISE ( $Name ) { WRITE-HOST “$Name is the Greatest Administrator on the Planet!” }

WRITE-HOST ‘ABC Corporation – Powershell Administration Console’
WRITE-HOST ‘’
WRITE-HOST ‘Use GET-HELP to errrrrr….. well to GET-HELP’

------------- End Profile Here ------------------------------------------

Ok this profile is lame, really lame, COLOSALLY lame.   A little message on the screen and a new Function you can type called ‘GET-PRAISE’ to make yourself feel good.

But that’s all your profile is!  You can predefine Global functions (which could be standard Powershell scripts your normally use), common domain servers predefined or any number of things.

It’s only limited by your imagination.  And it’s easy to standardize and control. And remember…

The Power of Shell is in YOU!

Sean
The Energized Tech

Powershell

Powershell and WMI.  A perfect marriage (except for that little affair with vbScript but we’re going to steer CLEAR of THAT whole thing)

I was wondering just how fast my computer was.  If there was anyway to see how fast my machine based upon the new WINSAT scores.

What do you suppose is the possibility there is way to tell that?  EASILY?

With Powershell and WMI teamed together it’s too easy.

GET-WMIOBJECT WIN32_WINSAT

Now of course it’s going to try and give us a bit too much information.  Here’s the ones we’re really interested in.  But really we just want the IMPORTANT stuff.  A quick SELECT-OBJECT or proper FORMAT-TABLE will show you what you want.

GET-WMIOBJECT WIN32_WINSAT | SELECT-OBJECT CPUSCORE,D3DSCORE,DISKSCORE,GRAPHICSSCORE,MEMORYSCORE

or

GET-WMIOBJECT WIN32_WINSAT | FORMAT-TABLE CPUSCORE,D3DSCORE,DISKSCORE,GRAPHICSSCORE,MEMORYSCORE –autosize

So why is this useful?  The ability to read the WINSAT score can tell you if a system is running as optimally as it can or more importantly if it’s up to the task of the Aero Desktop. 

Yes.  You can tell this remotely without logging in and spending hours on Inventory.  Running this command

GET-WMIOBJECT WIN32_WINSAT –computername SOMECOMPUTER | SELECT-OBJECT WINSATASSESSMENTSTATE, WINSPRLEVEL

Will allow you to tell whether an assessment has been run (WINASSESSMENTSTATE will yield a ‘1’ if it has) or the WINSPRLEVEL (Your overall WINSAT score)

Hint:  If you see a WINASSESSMENTSTATE that isn’t ‘1’ with a WINSPRLEVEL of 1.0; good chance the Assessment has never been run and THAT is the reason your user can’t use the cool new features in Vista or Windows 7.

Now you can sit back and remotely check out your systems abilities and capabilities all thanks to Powershell and WMI.  The world’s more INEXPENSIVE hardware inventory!

The Power of Shell is in YOU!

Sean
The Energized Tech

Powershell

Some days with Powershell we’re productive, some days we have fun.  Some days we mix in a little of both.

Today we’re going to see what fun we can have with the ComObject “Shell.Application”.  This single Com.Object is your entryway to almost everything tied to Windows Explorer.

Well maybe not absolutely everything but a lot of fun and maybe not so productive things.

We’ll create a link to the ComObject in the normal fashion

$EXPLORER=NEW-OBJECT –Comobject “Shell.Application”

Once complete we run a GET-MEMBER against it to see what’s inside Pandora’s box.

image

… After picking yourself up from the floor from that woozy fainting spell you’ll see there is actually quite a bit you can do with this.   Let’s try a little one.

$EXPLORER.Explore(“C:\”)

With any luck, you’ll now be staring at a window opened up on your screen showing you the “C:” drive initiated from Windows Explorer.  Next try a

$EXPLORER.Minimizeall()

Yes, sure enough, all the Windows are now minimized. (Including your Powershell Console!)

$EXPLORER.UndoMinimizeAll()

Trying this

$EXPLORER.WindowSwitcher()

Now you’re seeing the Windows Task Switcher, or if you’re running an Aero Desktop, Aero Flip.

$EXPLORER.CascadeWindows()

The point of this post is two things.  One; Have a little fun with Powershell and Two for you to discover how easy it is to play with ComObjects and discover their abilities within.   Run a Little GET-MEMBER on your results and you’ll be surprised how far down the rabbit hole goes.

The Power of Shell is in YOU

Sean
The Energized Tech

Powershell

Need to create a shapshot of something before playing with the operating system?  Or how about you’re doing something in Powershell and would like to have the ability to step back in time in the file system BEFORE you make that change?

I was digging through the old sample vbScripts from “Hey Scripting Guy” and found one in vbScript.   But as always, I like to see how it works in Powershell.  Especially if it’s a WMI script.  It also presumes you already have Shadow Copy enabled.  So the ORIGINAL sample to create a shadow copy with vbScript looked like this.

vbScript Code

Const VOLUME = "C:\"
Const CONTEXT = "ClientAccessible"
 
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set objShadowStorage = objWMIService.Get("Win32_ShadowCopy")
errResult = objShadowStorage.Create(VOLUME, CONTEXT, strShadowID)

If you have Shadow copy enabled, it’s a single one liner through WMI

(Get-WmiObject -list win32_shadowcopy).Create("C:\","ClientAccessible")

Just substitute in C: for the drive you’re doing a shapshot of.  This of course presumes Shadow Copy is already enabled on the drive in Question.

If you’d like this can easily be made into a Function you can drop into a script or your Powershell Profile.

function global:CREATE-SHADOW ( $Drive ) { (Get-WmiObject -list win32_shadowcopy).Create($Drive,"ClientAccessible") }

So yes, you can do it in vbScript; but converting to Powershell is almost painless

The Power if Shell is in YOU

Sean
The Energized Tech

Powershell

“…I stare about me.  OBJECTS are piped all over the place.  The VERB-NOUN resounded in my head.  (GET-PROCESS CSCRIPT | REMOVE-OBJECT) –or (GET-PROCESS YOU | REMOVE-OBJECT).  The words were clear.  End this Torrid affair with vbScript or find myself playing the BLUES as Powershell shunned me forever… There was only one choice.  A Final GET-FLING with vbScript and then … goodbyte…”

So we’re going to touch on some minor pieces of Syntax to get this out of our system.  No you won’t be an expert in vBscript from reading this.  But hopefully you’ll have just enough to muddle through the thousands of scripts to glean some useful knowledge.

I will point one of the BIGGEST thing that tripped me on vbScript.

This stupid little “_”

You see it all over the place in vbScript and it’s just MADDENING until you realize all it is.  A placeholder.  A little piece that says “Hey this line is too darn big to fit on one screen, so we’re going to break it up”

Powershell has the same feature.  Only in Powershell we use it all the time.  For us it’s the Backtick

----> `

Yes, that “Backward’s single quote thingy”

But knowing that that is all there job helps’ us read the vbScript and make it more legible.  I agree, breaking the lines up is a good idea.  But sometimes when you’re translating it needs to be in a single line for it to make sense to us.

At least it does to me.

So looking at this little batch of nightmare from last time….

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")

Read’s actually like THIS if you remove those little “_” Underscores breaking up the lines.

Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk")

Another thing that drove me bananas in vbScript was all of the “&” characters everything.   Never could make sense of them.  Turns out they’re not so bad either.  That Ampersand character is just another way of saying “And this”.

So a thing like this in vbScript that reads

This=”Something”
That=”Another thing”
OtherThing=”Something else completely Pointless”

wscript.echo This & “  “ & That & “---“ & Otherthing

Really is just this in Powershell

$This=”Something”
$That=”Another thing”
$OtherThing=”Something else completely Pointless”

Write-Host “$This  $That---$Otherthing”

Really it’s not a huge mystery language.   Just a slight difference in Syntax.  Once you unlock the little pieces, it’s actually pretty easy to redo vbScript into Powershell.

And now, if you all with pardon me, I need to create a “SEND-FLOWERS” function along with some “GET-FORGIVENESS” piped into.  I’m certain Powershell will forgive me this transgression… Someday.   If others learn because of this.  It will be worth it.

I will gladly suffer the punishment then.

Just remember

The Power of Shell is in YOU

Sean
The Energized Tech

Powershell

 

Hey wouldn’t you like a nice way to pull the Service tag from that Dell computer WITHOUT bothering the Vice President?

If you have at least good naming convention in your network it’s easy.  Here’s a function you can add to your Powershell Profile called “GET-SERVICETAG”.  It will query a computer via WMI and show the Service Tag.   Should work with about any Dell as long as WMI is enabled.

 

function global:get-servicetag ( $computername ) {

return $tag=get-wmiobject win32_bios -computername $computername | select-object SerialNumber

}

 

So with this added to your profile you can now execute a

GET-SERVICETAG NetBiosName

Where NetBiosName is the name of the computer in question and it will show the Service Tag.   I’ve enabled this function to return the tag as well so you CAN actually run this in a script against a series of computers too!

The Power of Shell is in YOU

Sean
The Energized Tech

Powershell

“…today Powershell connected to my Outlook libraries and pulled down my email objects.  I couldn’t explain away all the WENDS or FOR any reason could I determine what would happen NEXT.  My options are look DIM. I had better GET-PROCESS CSCRIPT | STOP-PROCESS and GET-CHILDITEM –recurse –include *.vbs | REMOVE-OBJECT before Powershell does a REMOVE-ITEM on me… This has gone far enough…I love Powershell too much.”

So we will take one last dip into the land of vbScript.  One tiny view of the loopiness aspect of it.

Earlier we mentioned the “FOR NEXT” loop and how it translated in Powershell.  What is interesting and nice (and VERY important to know) is that vbScript ALSO has a FOREACH loop to pass through a collection of objects.   It functions almost identical to Powershell.

So here’s a typical “FOREACH” loop in vbScript that will list all the Logical Drives as well as their Free Space and Size on a computer.

On Error Resume Next

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")

For Each objItem in colItems
    Wscript.Echo "Computer: " & strComputer
    Wscript.Echo "Drive Letter: " & objitem.Name
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Free Space: " & objItem.FreeSpace
    WScript.Echo
Next

As convoluted as that appears, really all the first series of lines

Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_LogicalDisk")

is just THIS in Powershell

$strcomputer=’localhost’ 

$colItems=GET-WMIOBJECT –query “Select * from Win32_LogicalDisk” –computername $strcomputer

This is one of the ways where Powershell beats vbScript.  It has a much more integrated way of handling and querying WMI.

So looking at the FOREACH loop in vbScript which is

For Each objItem in colItems
    Wscript.Echo "Computer: " & strComputer
    Wscript.Echo "Drive Letter: " & objitem.Name
    Wscript.Echo "Size: " & objItem.Size
    Wscript.Echo "Free Space: " & objItem.FreeSpace
    WScript.Echo
Next

 

In Powershell this SAME loop looks like this to manage the Objects

FOREACH ( $objitem in $colitems) {
     WRITE-HOST “Computer: $strComputer”
     WRITE-HOST “Drive Letter: $objitem.Name”
     WRITE-HOST “Size: $objitem.Size”
     WRITE-HOST “Free Space: $objitem.Freespace”
}

So really, the two Scripting languages in the way they handle loops are VERY similiar except for minor details in Syntax.  In knowing this, you should be able to build new Powershell Scripts while leveraging the established Power of past vbScript Masters.

Next time we’ll touch just a bit on some tiny details on Synatx and end this Torrid affair.

The Power of Shell is in YOU

Sean
the Energized Tech

Powershell

“Dear Diary

…I can hear the argument about to happen.  I’m slipping up.   In a fit of anger I burst out “It’s your GET-CHILDITEM that’s the CONST problem…”

Those words, uttering vbScript’s very language within the house, echoed through the walls.  This won’t be the last I hear of this.   Dear Powershell I am so sorry to have offended thee! *Sniff*

And so we delve further into vbScripting and get a little loopier today.  Remember last time we saw a For loop in vbScript, it wasn’t all that different from Powershell really.   Which means it isn’t that hard to do a direct tranlation of vbScript to Powershell of any legacy scripts you find.  In doing so, you may learn more about Powershell and how IT can interface with Windows thanks to the art of the GrandMasters of vbScript.

There are two other loops like Powershell has.  In Powershell we have a Do WHILE and Do UNTIL loop.   Well son of a gun, we’ve them in vbScript as well!

The Do WHILE loop executes a series of lines “WHILE” a condition is TRUE.  The DO UNTIL loop executes a series of instructions UNTIL it is TRUE.   Really honestly, they are almost identical and useful in different respective situations.

Here’s a basic Do While in vbScript

COUNTER=1

Do
   WScript.Echo COUNTER
   COUNTER = COUNTER + 1
Loop While COUNTER < 20

This is a very simple Do While in vbScript that will count up to 20 and display the output WHILE the variable ‘COUNTER’ is less than 20.  This same code in Powershell would look like this

$COUNTER=1

DO {
    $COUNTER
    $COUNTER=COUNTER + 1
} WHILE ( COUNTER –lt 20 )

Really only a few minor changes in the Syntax.  It’s still the same loop and works identically.   The other loop is the DO UNTIL which in vbScript would look like this.

COUNTER=1

Do
   WScript.Echo COUNTER
   COUNTER = COUNTER + 1
Loop UNTIL COUNTER = 20

In Powershell that same loop would appear like this

$COUNTER=1

DO {
    $COUNTER
    $COUNTER=COUNTER + 1
} UNTIL ( COUNTER –eq 20 )

There you go!  Done!  One important note though.  In vbScript the “UNTIL” and the “WHILE” statements can exist BEFORE or AFTER the CODE block.   It is very important to know this because when it exists BEFORE the codeblock in vbScript, the Codeblock ONLY executes if the Condition is True.   In the previous examples (in both cases) the Code will execute at LEAST once even if the condtion is already TRUE.  In both these cases the evaluation happens after.   This can be mimicked in Powershell with a simple “IF” statement although not as efficient.

So in THIS example

COUNTER=21

Do UNTIL COUNTER > 20
   WScript.Echo COUNTER
   COUNTER = COUNTER + 1
Loop

Will never execute because it happens BEFORE the code block.  A twin to this in Powershell would be

$COUNTER=1

IF ( $COUNTER –lt 20 ) {

$DO {
    $COUNTER
    $COUNTER=COUNTER + 1
} UNTIL ( COUNTER -gt 20 )

}

Now it’s not a typical scenario to encounter this but it IS very important to know the difference if you’re translating a vbScript to Powershell.  The Syntax is almost identical but knowing how the loop flows when you move the WHILE or UNTIL in vbScript is important.

We’ll end this loopiness with one final loop next time around.

And Remember, the Power of Shell is in YOU

Sean
The Energized Tech

Here’s a quick one for you.  You’ve got a Hyper-V core box and for whatever reason the Hyper-V Management Service won’t start.  Yields a 10048 Error about a port in use.

Fire up the Task Manager on the host to see if either VMMS.EXE is still running (Stuck in a stopped state) or you MAY see Dr Watson or the WERFAULT running in the background.

 

If you are truly stuck, do an end task on these three processes.  It will not affect the Child Partitions as they are running off the Hyper-Visor.   But it should allow you to Start or Restart the VMMS (Hyper-V Virtual Machine Management Service) without having to reboot the entire Core box.

Handy to know if you’re stuck in a jam.  Rebooting Production machines in the middle of the day is never an ideal option.

Cheers

Sean
The Energized Tech

Powershell

Today started out really nice.   I had the day off.   The Wearther was beautiful and a really nice email came my way.

Microsoft just awarded me the “Microsoft Most Valuable Professional (MVP)” in Powershell.  I saw the email and halfway between crying and laughing out loud in Joy.  I have never felt so honoured in my entire life.

Right off the bat, I have to extend thanks to my many friends who were a HUGE part of this happening.  My very desire to help change and improve things came directly from their encouragement and you the community for cheering me on.

What is the MVP Award?  It’s Microsoft’s way of recognizing people who give of themselves in the Community, in their knowledge, in their time and sometimes in different ways.   I may even be oversimplifying the award.    But all the same, it is truly an honour to receive it.  I am VERY grateful.

Now if you’re like me, the first time you saw an MVP you might have thought “Wow, I don’t think I could ever do that…” then you’re wrong.   An MVP is inside each and everyone of us out there.   I am exactly like you.   I just learned to take some chances and make mistakes, learn and grow. 

That very power is inside of YOU as well. 

So go ahead, engage the community.  Be a little nicer to the guy next door.   Don’t be afraid to present and make some mistakes.  You have the ability and it’s there all along.   Don’t convince yourself otherwise.  I once did that and felt that way.

Until one day, barely three years ago I heard a little voice tap me on the shoulder.

“Hey you’re just like us!”

Sean
The Energized Tech
MVP Powershell

MVPLogo

Powershell

Just realized.  I have a problem.

A BIG Problem.

I love Powershell.  It’s affecting my marriage.   It’s affecting my work life. 

It’s just too damn smooth.

So how do YOU know if you’re in Love with Powershell and potentially cheating on your wife / Better half / Worse half / Other half / None of the Above

I found a checklist.   You need to compare against this list

  • You have Jeffrey Snover on SpeedDial
  • You wrote an Ode to Bruce Payette
  • You keep calling Marco Shaw to ask him what the Hex codes for “Powershell Blue” are
  • When you see Kirk Munro?  You gasp “It’s HIM!” and faint dead on the floor
  • You can quote every interview from Powerscripting.NET and can perfectly mimic Hal and Jon
  • Most people are listening to Green Day.  You’re listening to “Highway to Powershell”; the Bad version.
  • You have Ed Wilson and Craig Liebendorfer on Baseball cards with their Script Stats
  • You called Dr. Tobias Weltner to your house for a checkup, just cuz
  • When you hear “MOW” you say “Oh Mighty MOW, Bless us with thy Wisdom” and then scream out SEND-MESSAGE
  • You refuse to use RSAT and only use Quest AD and Active Directory Modules screaming “GUI! Inefficient! CRUSH IT!”
  • You look at your Twitter Following.  98% of them are Gurus from Powershell.
  • The #Powershell hashtag alerts you via email, SMS, Phone, Satellite, Smoke Signal and direct brain implant.
  • You refuse to use the Start Menu.  All apps are loaded with “INVOKE-ITEM”
  • You doggedly pursue trying to find a copy of Ragnar Harper singing on Stage at Heroes Happen {HERE} in Norway
  • You search the shoe store for only one brand, “Power Boots”
  • You spend all day arguing with the Microsoft Learning program about a Powershell Cert
  • Having “the Blues” makes you EXTREMELY happy.
  • and finally
  • If you hear your wife is pregnant, you try to schedule a “GET-CHILDITEM” to time up the birth.

Smile!  The Power of Shell is in YOU

Sean
the Energized Tech