PowerShell for Windows Admins

March 25, 2012  5:09 AM

UG meeting reminder – March 2012

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Quick reminder that the UK user group meeting is on Tuesday 27 March @ 7.30 BST.  Details from



The meeting is on the new CIM functionality in PowerShell v3.  This is a need to know technology as much of the new PowerShell functionality in Windows Server 8 is based on this.

Please double check the time as the UK switched to daylight saving time this weekend.

March 21, 2012  4:32 PM

PowerShell Deep Dive

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I heard at the beginning of the week that I’ve been granted a speaker slot at the PowerShell Deep Dive next month – http://www.theexpertsconference.com/us/2012/

I’ll be speaking on creating cmdlets from WMI objects using a new feature in PowerShell v3 that is so cool it could start a new Ice Age

Look forward to seeing you there

March 21, 2012  3:14 PM

Folder sizes

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Question on the forums related to folder sizes and last write time

Get-ChildItem -Path "C:\PersonalData\MyBooks\PowerShell and WMI" -Recurse |             
where { $_.PSIsContainer} |            
foreach {            
 $size = Get-ChildItem -Path $_.FullName | measure -Sum Length | select -ExpandProperty Sum            
 Add-Member -InputObject $($_) -MemberType NoteProperty -Name Size -Value $size            
 $_ | select Fullname, LastWriteTime, @{N="Size(MB)"; E={[math]::Round(($_.Size/1mb), 2)}}            
} | Format-Table -AutoSize -Wrap

Unfortunately the object returned by get-ChildItem doesn’t include folder size. So we loop through each folder & get the sum of its contents. The size value is added to the folder object and Fullname, LastwriteTime and size displayed.  The size is recalculated to megabytes. Substitute your favourite size

March 19, 2012  4:33 PM

Reading registry values with CIM

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

In this post


and its predecessors we saw how to enumerate registry sub-keys. But how do we read a registry value?

function get-CIMRegValue{             
param (             
 [ValidateSet("HKCR", "HKCU", "HKLM", "HKUS", "HKCC")]            
 [Validateset("DWORD", "EXPANDSZ", "MULTISZ", "QWORD", "SZ")]            
switch ($hive){            
"HKCR" { [uint32]$hdkey = 2147483648} #HKEY_CLASSES_ROOT            
"HKCU" { [uint32]$hdkey = 2147483649} #HKEY_CURRENT_USER            
"HKLM" { [uint32]$hdkey = 2147483650} #HKEY_LOCAL_MACHINE            
"HKUS" { [uint32]$hdkey = 2147483651} #HKEY_USERS            
"HKCC" { [uint32]$hdkey = 2147483653} #HKEY_CURRENT_CONFIG            
switch ($type) {            
"DWORD"     {$methodname = "GetDwordValue"}            
"EXPANDSZ"  {$methodname = "GetExpandedStringValue"}            
"MULTISZ"   {$methodname = "GetMultiStringValue"}            
"QWORD"     {$methodname = "GetQwordValue"}            
"SZ"        {$methodname = "GetStringValue"}            
$arglist = @{hDefKey = $hdkey; sSubKeyName = $key; sValueName = $value}            
switch ($psCmdlet.ParameterSetName) {            
 "UseComputer"    {$result = Invoke-CimMethod -Namespace "root\cimv2" -ClassName StdRegProv -MethodName $methodname  -Arguments $arglist -ComputerName $computer}            
 "UseCIMSession"  {$result = Invoke-CimMethod -Namespace "root\cimv2" -ClassName StdRegProv -MethodName $methodname  -Arguments $arglist -CimSession $cimsession }            
 default {Write-Host "Error!!! Should not be here" }            
switch ($type) {            
"DWORD"     {$result | select -ExpandProperty uValue}            
"EXPANDSZ"  {$result | select -ExpandProperty sValue}            
"MULTISZ"   {$result | select -ExpandProperty sValue}            
"QWORD"     {$result | select -ExpandProperty uValue}            
"SZ"        {$result | select -ExpandProperty sValue}            
Displays a registry value

Displays a registry value using WSMAN or DCOM 
to access remote machines 

Hive Name. One of "HKCR", "HKCU", "HKLM", "HKUS" or "HKCC"
The name is validated against the set

The registry key - without the hive name e.g.

The specific registry value to return for the 
given key

The type of registry value to return.
Must be one of

.PARAMETER  computer
Name of a remote computer. Connectivity will be by WSMAN.

.PARAMETER  cimsession
An object representing a cimsession. Connectivity is controlled 
by the CIM session and can be WSMAN or DCOM

get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value DelayedAutoStart -type DWORD

get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value ObjectName -type SZ  

get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value DependOnService -type MULTISZ 

get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value ImagePath -type EXPANDSZ

get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value DelayedAutoStart -type DWORD -computer "."

$cs = New-CimSession -ComputerName Win7test  
get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value DelayedAutoStart -type DWORD -cimsession $cs   

$opt = New-CimSessionOption -Protocol Dcom                                                                                                          
$csd = New-CimSession -ComputerName server02 -SessionOption $opt                                                                                    
get-CIMRegValue -hive HKLM -key "SYSTEM\CurrentControlSet\services\BITS" -value DelayedAutoStart -type DWORD -cimsession $csd




Parameters define the hive, key, value to be read and the type of value.

Registry values come in a number of types:

  • DWORD and QWORD are 32 & 64 bit numbers
  • SZ is a string
  • EXPANDSZ is a string containing environmental variables that gets expanded
  • MULTISZ is a multi-valued string

Parameters to define a computer name or CIM Session are also present

The numeric value for the hive is set in a switch statement. The data type is used to define the method name – each data type has its own method.

The argument list is populated and the method is invoked using a computer name or CIM session as appropriate

The results are decoded according to type.

Full help is provided on the function.

March 18, 2012  2:30 PM

Get Global Catalog from DNS

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

One option for finding global catalog servers is often overlooked – DNS.  In an AD environment DNS stores the SRV records that advertise the services domain controllers can deliver

$dnsserver = "dc02"            
Get-WmiObject -Namespace 'root\MicrosoftDNS' -Class  MicrosoftDNS_SRVType `
-ComputerName $dnsserver -Filter "ContainerName = 'Manticore.org'" |             
Where {$_.OwnerName -like "_gc*"} |            
select TextRepresentation

We are interested in the ‘root\MicrosoftDNS’ name space and the MicrosoftDNS_SRVType records. We want the manticore.org zone and all records where the Ownername is like “_gc*”

The results look like this

_gc._tcp.Site1._sites.Manticore.org IN SRV 0 100 3268 dc02.manticore.org.

_gc._tcp.Site1._sites.Manticore.org IN SRV 0 100 3268 server02.manticore.org.  
_gc._tcp.Manticore.org IN SRV 0 100 3268 dc02.manticore.org.                                                     
_gc._tcp.Manticore.org IN SRV 0 100 3268 server02.manticore.org. 

March 16, 2012  4:24 PM

Up coming User group sessions

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

The sessions for the next few months are:

  • 27 March – PowerShell v3 CIM cmdlets and “cmlets over objects”
  • April – Managing Windows Server 8 with PowerShell
  • May – Managing Windows Server 8 with PowerShell

No thats not a mistake – there is so much new PowerShell functionality in Windows server 8 that two sessions will just scratch the surface.  I’m delivering the April session and PowerShell MVP Jonathan Medd is delivering the May session.

Details on March’s sessions from


As always the session will be recorded and made available afterwards.

March 15, 2012  4:25 PM

Active Directory WMI provider

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I stumbled on this namespace on my domain controller – root\directory\ldap – which appears to be a WMI provider for AD. From the information at http://technet.microsoft.com/en-us/library/hh831568.aspx it appears that it is being deprecated in Windows Server 8. This means it will be removed in a future version. In the mean time we have more toys to play with. Managing AD with the PowerShell cmdlets is going to be the best way to do it but we have an opportunity to experiment and discover other ways of doing things.

The namespace is huge so getting a full listing of classes is problematic.

Some quick observations

Get-WmiObject -Namespace root/directory/ldap -Class ds_grouppolicycontainer | select DS_displayName

gets a list of group policies

The domain security policy can be exposed like this

Get-WmiObject -Namespace root/directory/ldap -Class ds_domain | select DS_lockoutDuration, DS_lockOutObservationWindow, DS_lockoutThreshold, DS_maxPwdAge, DS_minPwdAge, DS_minPwdLength, DS_pwdHistoryLength, DS_pwdProperties

DS_lockoutDuration          : -600000000
DS_lockOutObservationWindow : -600000000
DS_lockoutThreshold         : 25
DS_maxPwdAge                : -36288000000000
DS_minPwdAge                : 0
DS_minPwdLength             : 7
DS_pwdHistoryLength         : 24
DS_pwdProperties            : 1

It will be worth poking around a bit more in this namespace

March 13, 2012  12:11 PM

PowerShell–Good Scripts guide

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Ed Wilson, the Microsoft Scripting Guy, wrote recently http://blogs.technet.com/b/heyscriptingguy/archive/2012/03/08/2012-scripting-games-judging-criteria-revealed.aspx

about the judging for the 2012 games.

At the top of that post there is a section labelled General criteria for good Windows PowerShell scripts.

I would strongly recommend everyone who is working with PowerShell, whether you intend to enter the games or not, to read that section and apply it to every script you produce.

The advice doesn’t get better than that!

March 11, 2012  11:22 AM

Setting a Network address in Windows Server 8

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


Windows Server 8 & Windows 8 bring a host of new functionality to us. I wanted to try out some of it so created a new VM and installed the OS – went for full GUI for now

Opened PowerShell and ran

Set-ExecutionPolicy remotesigned
Enable-PSRemoting -Force

The NetTCPIP module has some commands for working with network addresses

Get-NetIPInterface -ConnectionState Connected

ifIndex ifAlias            AddressFamily  NlMtu(Bytes)  InterfaceMetric Dhcp    Store
——- ——-            ————-  ————  ————— —-     —–
21      Virtual Wireless   IPv6           1500          5               Disabled Active
12      Virtual LAN        IPv6           1500          5               Disabled Active
21      Virtual Wireless   IPv4           1500          5               Disabled Active
12      Virtual LAN        IPv4           1500          5               Disabled Active

The display is abridged to fit

The important points are the ifIndex and ifAlias.  The index scheme is totally   different to the Win32_NetworkAdapter*  scheme

To set the address

New-NetIPAddress -InterfaceAlias "Virtual Wireless" -IPv4Address -PrefixLength 24 -DefaultGateway

Set-DnsClientServerAddress -InterfaceAlias "Virtual Wireless" -ServerAddresses
Set-DnsClient -InterfaceIndex 21 -ConnectionSpecificSuffix beta8.test

Notice that you have to use New-NetIPAddress. The logic seems to be that you are adding a new address to the adapter so use New*.

Set-NetIPAddress works to modify an existing address BUT you can’t change the default gateway that way!

The Set-DnsClient* cmdlets are in the DnsClient module

All of these cmdlets are based on calls to WMI classes

At the end of all that I wanted to bounce the machine any way so used


March 11, 2012  8:40 AM

PowerShell books–March 2012

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Back in January last year I posted about my preferred set of PowerShell books. http://msmvps.com/blogs/richardsiddaway/archive/2011/01/09/powershell-books.aspx

Its time to update that list

I’ll start by removing the first edition of books where the second edition is now available. As with the previous post these are books that I’ve read or been involved with in one way or another.

NOTE: This is my own highly subjective list. There are other books available. Some I have looked at and won’t recommend; others I have not yet looked at. I am also restricting my list to English language books. I will not recommend a book I haven’t read


Title Author Publisher ISBN
Learn Windows PowerShell in a Month of Lunches Don Jones Manning 978161790213
PowerShell v3 in Depth. An administrator’s guide. Don Jones
Richard Siddaway
Jeffery Hicks
Manning 9781617290558
Windows PowerShell Scripting Guide Ed Wilson Microsoft Press 9780735622791
Windows PowerShell Cookbook
Second Edition
Lee Holmes O’Reilly
Windows PowerShell 2.0 Best Practices Ed Wilson Microsoft Press 9780735626461
PowerShell in Practice Richard Siddaway Manning 9781935182009
PowerShell and WMI Richard Siddaway Manning 9781617290114
Managing Active Directory with Windows PowerShell
Second edition
Jeffery Hicks Sapien Press 9780982131442
Managing VMware Infrastructure with Windows PowerShell Hal Rottenberg Sapien Press 0982131402
VMware vSphere Power CLI Reference Luc Dekens, Alan Renouf, Glenn Sizemore, Arnim van Lieshout and Jonathan Medd Sybex 9780470890790
PowerShell in Action
Second Edition
Bruce Payette Manning



Learn Windows PowerShell in a Month of Lunches by Don Jones. It is a beginners guide to PowerShell. If you haven’t used PowerShell before this is the place to start. It will take you through the basics of using PowerShell from scratch. At the end of this book you will know what you are doing with PowerShell and have a good idea of how to learn more.

PowerShell v3 in Depth. An administrator’s guide by Don Jones, Jeffery Hicks and myself, is currently being written, and builds on Don’s Lunches book. It is designed to parallel and underpin the domain specific books such as PowerShell and WMI or Managing AD with Windows PowerShell. The book covers  PowerShell v2 and v3 (including all new features). Its premise is showing the administrator how to get the most out of PowerShell and how to work with it so the domain specific pieces for AD, Exchange or WMI are easy to slot into the PowerShell structure they know and understand. Expect it sometime after PowerShell v3 is available.

Windows PowerShell Scripting Guide by Ed Wilson. This takes over where Don’s book stops. It supplies a good introduction to automating basic windows admin tasks with PowerShell

Windows PowerShell Cookbook by Lee Holmes. Now in its second edition it supplies a lot of scripts for using PowerShell. This book is PowerShell orientated and doesn’t cover using Exchange, AD etc. The techniques are useful for using with some of the more advanced or technology specific books. Read this if you want to know how to do something with PowerShell – in terms of using the language for example removing members from an array

Windows PowerShell 2.0 Best Practices by Ed Wilson. Builds on his Scripting Guide and contains good information on designing and testing scripts. Even if you don’t agree with all of the ideas they are worth reading to make you think about how you want to perform these tasks in your organisation. I find my self dipping into this for Ed’s ideas. It is well worth having on your book shelf.

PowerShell in Practice I wrote as a “PowerShell for Administrators” book. Contains lots of examples for working with AD, WMI, DNS, IIS, Exchange, SQL Server and Hyper-V. I wrote it but I still refer to it for syntax & ideas. Predominantly based on PowerShell v2 it is still very applicable today.

PowerShell and WMI will be available soon. WMI is a really powerful technology but the lack of documentation and the difficulty of using it in the past has meant admins have been reluctant to use it. This book is designed to shine a light on to WMI, make it accessible and provide many ready to use scripts. It also covers the new WMI based functionality in PowerShell v3 – the CIM cmdlets and how to turn WMI classes into PowerShell cmdlets. Very relevant as much of the new PowerShell functionality in Windows Server 8 is based on that model.

Managing AD with Windows PowerShell by Jeffery Hicks. Now in its second edition. Mainly based around the Microsoft and AD cmdlets, this overlaps with PowerShell in Practice to some extent but if you just want to automate AD then start here.

Managing VMware Infrastructure with Windows PowerShell by Hal Rottenberg. If you are using VMware you need this. Admin becomes a lot easier.

VMware vSphere PowerCLI Reference by Luc Dekens et al. takes a slightly different view to Hal’s book. It is more a book about managing the whole VMware infrastructure from installation onwards. Personally I use both.

PowerShell in Action by Bruce Payette. This is the book for the in depth details on the PowerShell language. If you want to know how and why PowerShell works the way it does this is the book for you. Be aware that it is an advanced text and is NOT recommended for PowerShell newcomers.

This is my view of the PowerShell book world. No doubt other people will have different views. If you think I’ve missed a book that should be on this list please let me know but I will only recommend books I have read.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: