Friday, 15 January 2016

PowerShell Calculated Properties

A little-known but very powerful feature in PowerShell is the ability to create your own properties and then use them as if they were built-in properties of whatever object you’re working with.  Let’s take a look at a real-world example where this feature came in handy for me.

I recently needed to find out in which OU each member of a group was.  You can get part of the way there by using the distinguishedName property for each user in the group but that also includes the user’s name at the beginning, for example:

CN=Mary McAfee,OU=Finance,OU=Accounts,dc=mydomain,dc=corp

Not too difficult to get just the OU from that – with a bit of string manipulation we can get rid of the CN= part and we’ll have just the OU.  The great thing about calculated properties is that we can make this calculated OU attribute a property of each user.  Let’s see how we do that in the script below.

001
002
003
004
005
006
007

param
(
   
$GroupName
)

$ou = @{Name = 'OU';Expression = {$($_.DistinguishedName).Substring(($($_.DistinguishedName).IndexOf(",") + 1))}}
Get-ADGroupMember $groupName -Recursive | select SamAccountName, $ou

 

On line 6 we create the OU property, give it a name and then tell Powershell how to calculate it in the “Expression” section.  To calculate our OU property, we’re simply taking the DistinguishedName property of the user and getting all the text after the first comma.  Then, on line 7 the magic happens.  All we have to do is tell PowerShell to the select the $ou variable we created in line 6 and our calculated property will be returned as if it was retrieved directly from AD as shown below.

 

image_thumb[2]

There you have it – an easy way to retrieve the OU of each account in a group using a very powerful PowerShell feature, calculated properties.