Don’t Be Afraid To Learn PowerShell, You’ll Need It & You’ll Learn To Love It!

As I started my career in IT doing data crunching, OLAP & development in VBA & VB5.00/6.0 it isn’t that surprising I’ve done most of my automation in VBScript. I’m very familiar with it and even in the Windows 2008 Core era it was very useful as we didn’t have .NET in it at that time, meaning no PowerShell (no, the unsupported hack to get it on there does not count).

The first real PowerShell use for me came with Exchange 2007. That worked out pretty well, but at the time we didn’t use it for much more than Exchange. Today, more and more I’m starting to use PowerShell versus VBScript. For one sometimes VBScript can’t get it done, it’s not being developed any more in its capabilities and two, PowerShell commandlets do pack a serious punch!

Since Windows Server 2008 R2 PowerShell has gotten better overall support and with Windows 8 it is everywhere, natively. That’s very good and it means we can do all we need to do now (well a whole lot of it) in PowerShell. And then I haven’t even mentioned the entire workflow support in Windows 8 PowerShell!  As an old VB guy I had to get over my dislike for curly braces. I also need to earn the different syntax and especially the way in which to use the programming constructs (control flow, sub routines, operators, data types).

A lot of people tend to focus on the one liners. These are great and powerful, but they often reminded me of the old discussion with C/C++ developers about code readability & maintainability.  For that purpose we don’t mind that the code is more verbose. One liners are not the goal  but they are fun. Just remember that all code, how small it may be, one day will have to be maintained. The more readable, logical and easy to understand it is, the better. The whole “self documenting” thingy Smile.  One liners do not always fit in here. But to demonstrate I have nothing against them I’ll show you a real easy example for all you out there dealing with the jump to PowerShell. If you get hooked on one liners just be sure to use them with reason and go visit the blog of Jeff Wouters , you’ll become good scripting buddies.

Let’s say in VBScript you needed to format a date in a specific way. In VBScript you have a very limited number of format option to use. So when you want something funky like “20120414” (YearMonthDay) as a date format you’d use a function that builds that string and pads the numbers with zero if needed. You can either write a generic function to handle all possible date needs or a custom/purpose built one for just the needs at hand.

Just to get the gist of this, it could look a bit like this:

WScript.echo FormatDateForMyNeed() PrivateFunction FormatDateForMyNeed () Dim sDate, sYear, sMonth, sDay sDate =Now() sYear =Year(sDate) sMonth =Month(sDate) IfLen(sMonth) =1Then sMonth ="0"& sMonth sDay =Day(sDate) IfLen (sDay) =1Then sDay ="0"& sDay FormatDateForMyNeed = sYear & sMonth & sDay End Function

Driven by “routine” & a VBScript background you could mash up some functions in PowerShell and make it a convoluted scripting exercise:

function BuildDate { $date=Get-Date $String= [string]$date.year $MONTH= [String]$date.month $String+= PadString "0"2$Month$DAY= [String]$date.day $String+= PadString "0"2$DAYReturn$String } function PadString ($PadChar, $PaddedLength, [String]$StringToPad) { $StringToPad= ($padChar* ($PaddedLength-$stringToPad.length)) +$stringToPadReturn$StringToPad } BuildDate

But PowerShell has way better date format support than VBScript and you can just write this:

Get-Date -format "yyyyMMdd"

Now that’s a one liner I have nothing against and yes, it saves a whole lot of effort. Sure this is a real simple example but it proves a point. Do your self a favor, take out a couple of hours a week and dabble around in PowerShell. You’ll add a valuable time saving tool to your inventory and gain a precious skillset Smile for a bright future! Need a good example? See this blog post by Janssen Jones to see some workflow goodness and what it can do.

Key Value Pair Exchange WMI Component Property GuestIntrinsicExchangeItems & Assumptions

Now that Windows 2008 R2 SP1 is being deployed some scripts to check whether the Integration Components (IC) in Hyper-V VM guests are upgraded came back on the radar screen. Host are being upgraded and thus the clients need upgraded IC as well. Now to check this for hundreds or thousands of guest we need some automation. PowerShell comes in handy for this and some neat scripts can be found around the internet. The most concise PowerShell code to do this, that I know of, is the one Peter Noorderijk (great Dutch IT Pro)  uses in his  PowerShell function Get-IntegrationServicesVersion on his blog How to check the version of the Integration Components.  As he provided this script just when I needed one I used it. This worked fine until I ran into an issue with it on some clusters. On two test clusters and two production clusters, it did the job as expected. On one test cluster and one production cluster, we ran into the situation where the output seemed wrong. The screenshot below is an example of this.

The red arrows indicate wrong data for the VMname and ICVersion. What happened here?  Well, when we read out the  GuestIntrinsicExchangeItems property from the WMI object Msvm_KvpExchangeComponent we get back XML. That XML needs to be parsed to display it for human consumption. The function depends on fixed positions containing the correct data. I’ve marked the relevant portions with a red arrow above, they come from$vmkvp[0] en $vmkvp[14] in the script below.

function Get-Integ.rationServicesVersion ($HVhost = $(throw “HVHost required”))
    {
    $kvps = Get-WmiObject -Namespace rootvirtualization -ComputerName $HVHost -Query “Select GuestIntrinsicExchangeItems From Msvm_KvpExchangeComponent”
        foreach ($kvp in $kvps)
         {
         $vmkvp = $Kvp.GuestIntrinsicExchangeItems
         $vmkvp | select-object @{Label=”VMHost”;Expression={$hvhost}},
                                @{Label=”VMName”;Expression={($vmkvp[0]).instance.property[1].value}},        
                                @{Label=”ICVersion”;Expression={($vmkvp[14]).instance.property[1].value}} -first 1
         }    
    }
  
foreach ($hvhost in get-content servers.txt) {Get-IntegrationServicesVersion $hvhost}

And indeed, when we dump the XML for two of the affected servers out to text files you can see the order is indeed different so counting on the exact location in an array is what tripped us up here.

Should this ever happen? Am I making a scripting mistake somewhere? Running a check with a VBScript that parses the XML  using XDOM (just in case my PowerShell skills are the cause of this) confirms the order is different but that the key pairs match up and are correct

D:SysAdminPowerShellScripts>cscript.exe test.vbs

Microsoft (R) Windows Script Host Version 5.8

Copyright (C) Microsoft Corporation. All rights reserved.

Guest OS information for server01

CSDVersion : Service Pack 1

FullyQualifiedDomainName : server01.lab.test

IntegrationServicesVersion : 6.1.7601.17514

NetworkAddressIPv4 : 10.10.100.118

NetworkAddressIPv6 : fe80::a177:729:8840:250%9

OSBuildNumber : 7601

OSEditionId : 7

OSMajorVersion : 6

OSMinorVersion : 1

OSName : Windows Server 2008 R2 Standard

OSPlatformId : 2

OSVersion : 6.1.7601

ProcessorArchitecture : 9

ProductType : 3

RDPAddressIPv4 : 10.10.100.118

RDPAddressIPv6 : fe80::a177:729:8840:250%9

ServicePackMajor : 1

ServicePackMinor : 0

SuiteMask : 272

D:SysAdminPowerShellScripts>cscript.exe test.vbs

Microsoft (R) Windows Script Host Version 5.8

Copyright (C) Microsoft Corporation. All rights reserved.

Guest OS information for server13

FullyQualifiedDomainName : server13.lab.test

OSName : Windows Server 2008 R2 Standard

OSVersion : 6.1.7601

CSDVersion : Service Pack 1

OSMajorVersion : 6

OSMinorVersion : 1

OSBuildNumber : 7601

OSPlatformId : 2

ServicePackMajor : 1

ServicePackMinor : 0

SuiteMask : 272

ProductType : 3

OSEditionId : 7

ProcessorArchitecture : 9

IntegrationServicesVersion : 6.1.7601.17514

NetworkAddressIPv4 : 10.10.100.112

NetworkAddressIPv6 : fe80::c18b:e3f2:7f05:31e4%12

RDPAddressIPv4 : 10.10.100.112

RDPAddressIPv6 : fe80::c18b:e3f2:7f05:31e4%12

When I look at where that data lives in the registry on those servers it all looks exactly the same, neatly ordered buy the RegEdit GUI:

So when getting that data from the Key-Value Pair Exchange WMI component with the property GuestIntrinsicExchangeItems you get a bunch of XML. That has to be parsed to be displayed in a readable fashion. The problem we are seeing is due to the fact that the items in the XML file are not in the same order. Peter’s function assumes it is. However this does not happen to be the case for most virtual machines, the majority is in the expected order. I don’t know why that is or if this is supposed to happen but it doesn’t seem to cause any harm. All is fully functional and operational in Hyper-V Manager, SCVMM 2008R2 … etc. Perhaps an MVP or Microsoft guru can shed some light on this. It seems like a bug waiting to happen if a developer of Hyper-V management software makes the same assumption. Of is this never suppose to happen and do I need to worry? I don’t know Smile I reinstalled the IC on the guests that have a different ordering and live migrated them, but that didn’t change anything

Anyway if you want to make sure you get the correct output we’ll need another approach that doesn’t make assumptions. You can roll your own and get the output customized to your needs but you need to parse the XML using a filter.  An example of this is listed below.

# Filter for parsing XML data
filter Import-CimXml 
{    
# Create new XML object from input  
$CimXml = [Xml]$_    
$CimObj = New-Object -TypeName System.Object     

# Iterate over the data and pull out just the value name and data for each entry   
foreach ($CimProperty in $CimXml.SelectNodes("/INSTANCE/PROPERTY[@NAME='Name']"))      
 {          
     $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE       
 }  
    
 foreach ($CimProperty in $CimXml.SelectNodes("/INSTANCE/PROPERTY[@NAME='Data']"))     
   
 {         
     $CimObj | Add-Member -MemberType NoteProperty -Name $CimProperty.NAME -Value $CimProperty.VALUE      
 }    


# you send the output from the property to the filter via a pipe
$KvpComponentVMGuest.GuestIntrinsicExchangeItems $vmkvp |Import-CimXml 

Maarten Wijsman (a fellow blogger at http://www.hyper-v.nu like Peter)  has a nice example script here that also uses a filter Import-CimXML. Do note that there are variants on this filter depending on what output you desire that explains the difference between the filters.

Calling x64 CLI Tools in x86 Scripting Tools and Processes

Every now and then I get the same question from people who only recently decided to make the switch to x64 bit Windows operating systems. I’ve been running on x64 since Vista RTM and I’m very happy with it. When those people start scripting with their tools, which are 32 bit, calling some CLI tool in %windir%System32 they can run into an annoying issue that express itself in the correct yet somewhat misleading “WshShell.Exec: The system cannot find the file specified.”. But you know it’s there in %windir%System32, you checked and double checked!

When your scripting tool is 32 bit and you run your script it usually launches an 32 bit version of the CLI tool you’re calling. This behavior is a result of file redirection. This is a transparent process that’s part of the Windows-on-Windows 64-bit (WOW64) subsystem that is used to run 32 bit apps. When a 32 bit applications calls a CLI tool in the %windir%system32 directory it silently redirects this to the %windir%SysWOW64 where 32 bit apps can happily run without a worry on an x64 bit operating system. Yes, indeed %windir%system32 is for x64 code only and %windir%SysWOW64 is for 32 bit code.

What’s in a name 🙂 Some people argue they should have use system32 for 32 bit and system64 for x64 bit but I’m sure they had their reasons for what they did (i.e. it would have been hell for some reason I guess). Other suggestions have also been made by people who are far better qualified than I am. For example by Mark Russinovich, a hard core systems developer, in http://blogs.technet.com/b/markrussinovich/archive/2005/05/07/running-everyday-on-64-bit-windows.aspx.

Now all this can happen transparently for the user if the tools used have both an x64 and a x86 version. Cmd.exe and ping.exe are fine examples. If you run some VBScript in my favorite scripting tool for example (Sapiens PrimalScript) which is 32 bit it will launch a 32 bit cmd.exe, that launches the cscript.exe 32 bit version and which will launch ping.exe (using WScript.Shell) in %windir%SysWOW64 by silently redirecting your %windir%system32 path. No worries, you don’t know any better and the result is the same. So it’s usually not a problem if there is both a x64 and a x86 version to the CLI tool as you have seen in the ping.exe example. When a 32 bit process calls a tool in %windir%system32 it’s redirected to %windir%SysWOW64 and uses the 32 bit version. No harm done.

The proverbial shit hits the fan when you call a CLI tool that only has a x64 bit version. As the scripting tool is x86 it’s call is redirected to the WOW64 and the script fails miserably as the CLI tool can’t be found. This can be pretty annoying when writing and testing scripts. The CLI backup tool of Windows Backup is a prime example. It does not have a 32 bit version. Consider this little script for example:

Option Explicit

Dim oShell
Dim oExecShell
Dim sBackupCommandString
Dim sText

Set oShell = CreateObject("WScript.Shell")
'sBackupCommandString = "%windir%sysnativewbadmin get disks"
sBackupCommandString = "%windir%system32wbadmin get disks"

Set  oExecShell = oShell.Exec(sBackupCommandString)

Do While oExecShell.Status = 0
    Do While Not oExecShell.StdOut.AtEndOfStream
        sText = oExecShell.StdOut.ReadLine()
        Wscript.Echo sText 
    Loop    
Loop

Set oShell = Nothing
Set oExecShell = Nothing

There is a lot of File Redirection going on here to %windir%SysWOW64 when running this code in the 32 bit scripting tool. That tool launches the 32 bit cmd.exe and thus the 32 bit cscript.exe which then launches a 32 bit shell and tries to run "%windir%system32wbadmin get disks" which is also redirected to %windir%SysWOW64 where wbadmin cannot be found throwing the error: “WshShell.Exec: The system cannot find the file specified.”. If you don’t have a 32 bit code editor just launch the script manually from an 32 bit command prompt to see the error.

The solution as demonstrated here is to use as in “%windir%Sysnativewbadmin.exe get disks”. Uncomment that line and put the line with sBackupCommandString = "%windir%system32wbadmin get disks" in comment. Do the same test again and voila. It runs. So there you have it, you can easily test your script now. Just make sure that when the time comes to put it out in the wild you replace it with the real path if the calling process is x64 bit, which for example wscript.exe and cscript.exe are when you launch the form a x64 bit shell (explorer.exe or cmd.exe), which is the default on a x64 operating system. The x86 version runs when you launch them from a x86 shell. But remember the default on x64 bit operating systems is x64 bit and sysnative only functions when called from a 32 bit process (it’s a virtual directory that doesn’t really exists).

Sysnative was introduced in Vista/Windows2008 x64 bit. Not only 32 bit script editor users a affected by this, all 32 bit processes launching tools in "%windir%system32 are. See more on MSDN via this link http://msdn.microsoft.com/en-us/library/aa384187(VS.85).aspx.  For the folks running XP or Windows 2003 x64 bit it is perhaps time you consider upgrading to Windows 2008 R2 or v7 x64 bit? If you can’t, no need to worry, you’re in luck. Microsoft did create a hot fix for you (http://support.microsoft.com/?scid=kb;en-us;942589) that introduces sysnative on those platforms. So welcome to the x64 bit universe, beware of file redirection in WOW64 and happy scripting 🙂