Forum Discussion
Borislav_Vit
Jul 27, 2023Copper Contributor
Help with PS script for computers in AD onprem
Hi guys,
I want to automate a task by adding new computers to the domain. By default, they appear in Computers OU and we have different OUs per office and computers. My idea is a script to run every 20 min as scheduled tasks which will check for new computers in the computers OU and then move computers to specific OU based on the name of the PC. For example, when a computer name begins with BN1-N- then it will be moved to Notebooks OU in BN1 OU, when computer name begins with KN1-W- then it will be moved to Workstations OU in KN1 OU and so on.
All solutions were related to Identity with specific computer name.
Is it possible to be done?
Thanks
- LainRobertsonSilver Contributor
Hi.
Yes, it's possible.
The following basic script will allow you to do this and would be fine for smaller environments.
For larger environments, you would want to invest some time in coming up with an algorithm for calculating the target organisational unit rather than using the mappings approach in the example below. It would be more complex to do but worth it in the long run.
Example script
# Create your computer name prefix-to-target location mappings. $Locations = @{ "BN1-N-" = "OU=Notebooks,OU=SomeRandomOU1,DC=yourdomain,DC=com"; "KN1-W-" = "OU=Workstations,OU=SomeRandomOU2,DC=yourdomain,DC=com"; } $SearchBase = "CN=Computers,$(([adsi]'LDAP://RootDSE').defaultNamingContext[0])"; Get-ADObject -Filter { (objectClass -eq "computer") } -SearchBase $SearchBase | ForEach-Object { $Computer = $_; foreach ($Key in $Locations.Keys) { if ($Computer.Name.StartsWith($Key, [System.StringComparison]::OrdinalIgnoreCase)) { $Computer | Move-ADObject -TargetPath ($Locations[$Key]); break; } } }
Cheers,
Lain
Edited: Uncommenting the intended search base line and removing my localised test line - both of which I should have done prior to posting.
- Borislav_VitCopper Contributor
the first test worked like a charm, thank you very much.
I will let it running today, and see if it works without any problem as scheduled task.
Thanks again.