PowerShell – AD auto move servers

To be a good AD admin you must be organized and lazy. By lazy I mean you make things easier on yourself – I don’t mean you slack or take shortcuts! One of the first scripts I wrote when I started my current job was one to take any new servers that got joined to the domain and move them automatically to the servers OU (by default – they go to the computers container). This ensures that they actually make it there and it saves us a few seconds of our time :]

A few notes:

  • You will notice I have a clause in there that checks to see if the name starts with ‘SQL’ as our SQL servers do – we also have them in their own OU. You may want to pay attention to that part and possibly modify it to your environment.
  • Be sure to enter the ldap url (use ‘dsquery <OU name>’ to find the path you need to enter)
  • The script won’t run if it doesn’t detect any “servers” in the computer container
  • Set this to run every 15 minutes
  • The user it runs as will need permissions in AD to move computer objects

_____________________________________________________________________


cls
Import-Module activedirectory
$ErrorActionPreference = "silentlycontinue"

###########
#Variables#
###########

$servers = get-adcomputer -LDAPFilter "(operatingSystem=Windows*Server*)" -SearchBase "<enter domain path>"
$servernames = $servers | select-object -expandproperty name
$Date = Get-Date

######
#Code#
######

If ($servers -eq $null)

    {
        exit
    }
elseif ($servers -ne $null)
    {

foreach ($s in $servers)
        {
        If ($s.name -like "SQL*")
            {
            Move-ADObject -Identity $s -TargetPath "<enter ldap url>"
            }
        Else
            {
            Move-ADObject -Identity $s -TargetPath "<enter ldap url>"
            }
        }
    Write-output "Date: $Date"
        Write-output ""
        Write-output "Machines:"
        Write-output ($servernames)
        Write-output "_______________________________"
    }

akers8806

Leave a Reply

Your email address will not be published. Required fields are marked *