List Servers, Workstations and Users using PowerShell and AD

I am writing a basic PowerShell script function to list all the servers, workstation and users list in your domain. It will be very helpful if your sysadmins ask you to find the count of the machines installed with specific OS version. Ex:  Windows Server 2008 R2.

1) I am writing a custom function to find servers list, the following function will list all the server name out of Active Directory. This could even be modified and fetch whatever property you have like.

Function Get-ServerList{
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter=”(&(objectcategory=computer)(operatingSystem=*Server*))”
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()

$Results | % {$_.Properties.name}
}

# We will store the count of all the servers in a variable as
$ServerCount = (Get-ServerList).Count

#Will display the count of servers in your environment
$ServerCount

#You can even export the list to an excel sheet as well
Get-ServerList >> C:\Server_List.xls

Note: You can even customize if you would like to find List of Servers specific to Windows Server 2008 R2, to achieve it we need to replace the value in function as below:

$Searcher.Filter=”(&(objectcategory=computer)(operatingSystem=*Windows Server 2008 R2*))”

2) Similarly, we can write a function to find the workstation list. Let’s extract the list of all the workstation with Windows 7.

Function Get-WorkStationList_ Windows_7{
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter=”(&(objectcategory=computer)(operatingSystem=*Windows 7*))”
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()

$Results | % {$_.Properties.name}
}

# We will store the count of all the Windows 7 machine in a variable as
$WorkstationCount = (Get-WorkStationList_ Windows_7).Count

#Will display the count of Windows 7 in your environment
$WorkstationCount

#You can even export the list to an excel sheet as well
Get-WorkStationList_ Windows_7 >> C:\WorkStation_Windows_7_List.xls

3) Finally, we can write a custom function to list all the users in your Active Directory.

Function Get-UserList{
$Searcher=New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter=”(objectcategory=user)”
$Searcher.PageSize = 1000
$Results=$Searcher.FindAll()

$Results | % {$_.Properties.samaccountname}
}

# We will store the count of all the users in a variable
$UserCount = (Get-UserList).Count

#Will display the count of users in your environemnt
$UserCount

#You can even export the list to an excel sheet as well
Get-UserList >> c:\Users_List.xls

Advertisements