Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, May 8, 2013

Retrieve a list of all Disabled Computer Accounts

I just helped a user with a big headache.  The user is new to PowerShell and was working way to hard.  First of all, I am impressed that this administrator was dipping into the .NET framework.  Take a look at his code.

$strfilter = "(&(objectClass=user)(objectCategory=person))"

 

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

 

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher

$objSearcher.SearchRoot = $objDomain

$objSearcher.PageSize = 1000

$objSearcher.Filter = $strFilter

$objSearcher.SearchScope = "Subtree"

$objSearcher.PropertiesToLoad.Add("cn") | Out-Null

$objSearcher.PropertiesToLoad.Add("member") | Out-Null

$objSearcher.PropertiesToLoad.Add("proxyAddresses") | Out-Null

$objSearcher.PropertiesToLoad.Add("displayName") | Out-Null

$objSearcher.PropertiesToLoad.Add("distinguishedname") | Out-Null

$objSearcher.PropertiesToLoad.Add("useraccountcontrol") | Out-Null

 

$users = $objSearcher.FindAll()

foreach ($user in $users)

{

"Testing $($user.properties.item(""distinguishedname""))"

"UAC: $($user.useraccountcontrol)"

if($user.useraccountcontrol -band 2) 

{ write-host -foregroundcolor red "`t account is disabled" } 

ELSE 

{ write-host -foregroundcolor green "`t account is not disabled" }

 

}

 

You have to admin, for a beginner, this is impressive.  The problem is that the Active Directory module would have greatly reduced his efforts.  Here is the code that he was looking for.

Get-ADComputer -Filter 'Enabled -eq $False' |


Select-Object -Property Name, Enabled

A little bit more refined and simpler to both use and understand.  This code also keeps the information as an object so the administrator can execute actions against these objects if needed.
 
 
 

No comments: