Script Tips
Shrinking Scripts
As if scripting couldn't get any easier, Microsoft refines it further with PowerShell.
This time out, I want to take a brief look at a PowerShell script. PowerShell is Microsoft's recently code-named Monad, which will ship with Exchange 12 (and eventually for Windows Vista, too). The neat thing about Exchange 12 is that all of its administrative functionality is built into PowerShell; the graphical administrative console just utilizes that functionality. So you can basically script anything that Exchange can do.
PowerShell is built atop the Microsoft .NET Framework, meaning the PowerShell cmdlets, as they’re called, are built in .NET. You don’t need to know .NET, though, because you use the cmdlets like special command-line utilities. For example, this:
$colItems = get-wmiobject -class "Win32_Service" '
-namespace "root\CIMv2" -computername "."
retrieves all instances of the Win32_Service WMI class from the root\CIMv2 namepsace on your local computer, and stores the instances as an array (or collection) in the variable $colItems. Did you catch the ' character at the end of line 1? It’s like the _ character in VBScript, telling PowerShell that the second line is really a part of the first line.
With the $colItems array populated, you can use a For...Each style loop to display the names of all the services:
foreach ($objItem in $colItems) {
}
write-host "Name: " $objItem.Name
}
The syntax is a lot like languages such as C# or Jscript, and there are some important things to note:
- The cmdlets always have a verb-noun name, like "write-host" and "get-wmiobject".
- You don’t need to declare variables like $objItem or $colItem in advance.
- There’s no string concatenation character! You just type what you want to show, and PowerShell figures it out. /li>
It’ll likely be a while before you really have to worry about PowerShell, but it never hurts to get a jumpstart! Want to learn more? Check out Jeffery Hicks’ blog at http://jdhitsolutions.blogspot.com/, and visit the Monad/MSH Scripting Forum at www.ScriptingAnswers.com. Next month, you'll also begin seeing my new "PowerShell Answers" column right here on MCPmag.com.
About the Author
Don Jones is a multiple-year recipient of Microsoft’s MVP Award, and is Curriculum Director for IT Pro Content for video training company Pluralsight. Don is also a co-founder and President of PowerShell.org, a community dedicated to Microsoft’s Windows PowerShell technology. Don has more than two decades of experience in the IT industry, and specializes in the Microsoft business technology platform. He’s the author of more than 50 technology books, an accomplished IT journalist, and a sought-after speaker and instructor at conferences worldwide. Reach Don on Twitter at @concentratedDon, or on Facebook at Facebook.com/ConcentratedDon.