Thursday, October 16, 2008

List all users or computers in the default domain in PowerShell

List all users or computers in the default domain in PowerShell

Sniff. My first PowerShell script. It's like being a new dad all over again.

Save the script with a .ps1 extension and run it via the Powershell command. The script accepts either the parameter USERS or COMPUTERS

$de = New-Object directoryservices.directoryentry('LDAP://rootDSE')
$Root = New-Object directoryservices.directoryentry("LDAP://$($de.DefaultNamingContext)")
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)

switch ($args[0]) {
"computers" {$searcher.Filter="(&(objectCategory=computer))"}
"users" {$searcher.Filter="(&(objectCategory=person)(objectClass=user))"}
default {"Please specify either USERS or COMPUTERS.";Exit}
}

$searcher.PageSize = 1500
$searcher.PropertiesToLoad.Add("cn")
$searcher.sort.PropertyName="cn"
$ADItems = $searcher.findAll()
foreach ($user in $AdItems){$user.properties.cn}

No comments: