
[Solved] how to manage the Active directory objects in certain OU ‘s using PowerShell step by step
list out the paths for the selected OU ‘s.
Write-Output “Discovering all computers in selected OU’s ” $ous = @( ‘OU=computers 1,OU=Servers,DC=test,DC=com’, ‘OU=computers 2,OU=Servers,DC=test,DC=com’, ‘OU=computers 3,OU=Servers,DC=test,DC=com’, ‘OU=computers 4,OU=Servers,DC=test,DC=com’, ‘OU=computers 5,OU=Servers,DC=test,DC=com’, ‘OU=computers 6,OU=Servers,DC=test,DC=com’, ‘OU=computers 7,OU=Servers,DC=test,DC=com’, ‘OU=computers 8,OU=Servers,DC=test,DC=com’ ) You can define the property values, for the example below we are getting the following values (Name, Description, operatingSystemVersion, distinguishedName) and this will export the list to a csv where you can use the same list to manage the objects for example disable and delete if needed.Define the list of objects to output from the selected OU’s using the loop
$adComputersResult = @() foreach ($ou in $ous) { $adcomputers = Get-ADcomputer -SearchBase $ou -Filter * -Properties * | Select-Object -Property Name, Description, operatingSystemVersion, distinguishedName, @{Name=’Members’;exp={(Get-adcomputer $_.SamAccountName | Select-Object -ExpandProperty SamAccountName) -join ‘,’}} $adcomputers | ForEach-Object { $adComputersResult += $_ } } $FormatEnumerationLimit=-1 $adComputersResult | Export-Csv -NoTypeInformation -Path:”C:\scripts\computers.csv”
Report end of script actions.
Write-Output “Discovery of all computers. Output saved to: $ computers”Disable Computers using the computers csv
Load the AD objects that were captured running the script above.$computers = Import-CSV C:\scripts\computers.csv ( this will load the all the object into PS memory)
ForEach ($Item in $computers){ $DistName = $Item.Name set-ADComputer -Identity $DistName -Enabled $false Get-ADComputer -Filter { Name -eq $DistName } | Select-Object Name, Enabled }
Delete Computers using the computers csv
You can use the belwo script to delete the objects if neededForEach ($Item in $computers){ $DistName = $Item.Name Remove-ADComputer -Identity $DistName -Confirm:$false Write-Output “$($Item.Name) – Deleted” }
The script is handy tool to do mass manage the AD objects. Thanks for reading this and I hope it has helped