Windows PowerShell


PowerShell Scripting  Active Directory Basics

Introduction to PowerShell Scripting - Active Directory

  ˚

Answer for: Example 4: Adding a Foreach Loop

Pre-requisites

  • Experiment with the foreach loop in isolation so that you understand its mechanism.
  • Research more LDAP properties.  For example the relationship between, GivenName (First name) and SN (Surname) and CN (Full name) .

# PowerShell Answer!
# Author: Guy Thomas
# Version 4.6 Sept 2007 tested on PowerShell v 1.0
$Dom = 'LDAP://DC=cp;DC=mosel'
$Root = New-Object DirectoryServices.DirectoryEntry $Dom
$i=0
# Create a selector and start searching from the Root of AD
$selector = New-Object DirectoryServices.DirectorySearcher
$selector.SearchRoot = $root
$adobj= $selector.findall() |`
where {$_.properties.objectcategory -match "CN=Person"}
foreach ($person in $adobj){
$prop=$person.properties
      if ($prop.sn -ne $Null){
      $i++
      Write-host "First name: $($prop.givenname) " `
      "Surname: $($prop.sn) User: $($prop.cn)"
      }  #Closing brace
}
"Total $i"

Learning Points

Note 1:  By adding a filter, you can fine tune the output.  This should result in a lower total as displayed by:
"Total $i".  Talking of this tiny instruction on the last line, if you try: "Total " $i, frustratingly, the script does not work.  "Total " +$i works but is long-winded.

Note 2:  Observe the dollar sign in front of $Null.  $Null is a special PowerShell variable.  Omit the dollar and it does not work.

Note 3:  Going back to basics, PowerShell uses minus eq and not an equals sign.  -eq would be correct.  My point is that the negative, not equal, is -ne  (and not -neq).

  ˚

Summary of PowerShell and Active Directory

It was with much relief that I discovered that PowerShell supplied a mechanism to query Active Directory.  The secret is starting with new-object, then choosing the specific Com objects, DirectoryServices.DirectoryEntry and DirectoryServices.DirectorySearcher.

See more Microsoft PowerShell tutorials:

PowerShell Home  • Com  • Shell Application  • Active Directory  • QAD Snap-in  • Get-Member

Please write in if you see errors of any kind.  Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Google

WebThis Site

Guy Recommends: SolarWinds Exchange Monitor

Exchange Monitor from SolarWindsHere is a free tool to monitor your Exchange Server

 

Home Copyright © 1999-2008 Computer Performance LTD All rights reserved

Please report a broken link, or an error.