Wednesday, 14 January 2009

Do more (or the same) with less...

One of the best the best things about Powershell (and there are many) is that it allows lazy IT Pro’s like myself to be just that: lazy, or in my case even lazier than normal. Someone on my team at work today asked me how to query an environment variable using VBS. Being as inherently lazy as I am my first answer was “I can tell you how to do it in Powershell” because I knew it was a one-liner, whereas VBS would require a bit more typing.
Say you needed to get the value associated with the environment variable PROCESSOR_IDENTIFIER. To achieve this in VBS you’d do something like…

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colEnvVar = objWMIService.ExecQuery _
("Select * from Win32_Environment where Name = 'PROCESSOR_IDENTIFIER'")

For Each objEnvVar in colEnvVar
wscript.Echo objEnvVar.Name & ": " & objEnvVar.VariableValue
Next

Granted it’s not the longest piece of code ever typed, but why wear your fingers out any quicker than you need to. To get the same information using Powershell all you need is…

get-childitem env:PROCESSOR_IDENTIFIER


get-childitem is usedto retrieve the items from the specified location which in this case is env: which is the Powershell environment provider, and PROCESSOR_IDENTIFIER specifies the relevant variable to report on. If you want to report on all variables, and type even less, try…

gci env:*


gci is the alias for get-childitem and the wildcard means all variables will be reported on.
So if you want to be able to start putting less effort into things, try Powershell.

No comments:

Post a Comment