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...
LainRobertson
Jul 27, 2023Silver 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_VitJul 28, 2023Copper 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.