Thursday, 16 November 2017

Powershell - move AD computers from cn=computers to different OUs selected by name

this powershell script will move new computers vom the default CN=computers to an OU selected by Name





import-module ActiveDirectory

$newComputers = (Get-ADComputer -SearchBase 'CN=Computers, DC=yourdomain, DC=local' -Filter *  -ErrorAction Stop | select -Expand DistinguishedName)

Foreach  ($computer in $newComputers)
    {


        if ($Computer.StartsWith("CN=ALF1") -or $Computer.StartsWith("CN=CAP1") -or $Computer.StartsWith("CN=ERK1"))
                {
                Write-Host "$Computer moved to Europe"
                Move-ADObject -Identity $Computer -TargetPath 'ou=Europe,ou=your Sub OU,DC=yourdomain,DC=local'
                }
        ElseIf ($Computer.StartsWith("CN=ATN1") -or $Computer.StartsWith("CN=CAR1"))
                {
                   Write-Host "$Computer moved to America"
                Move-ADObject -Identity $Computer -TargetPath "ou=America,ou=your Sub OU,DC=yourdomain,DC=local"
                }
        Else         {
                write-host "not matching"
                }
    }