Wednesday 20 February 2013

Powershell - Move computer to OU and add to group

Sometime ago I posted a script which queries the computer information and move it to a pre-defined OU based on the computer's type. It may be a laptop, desktop or VM.

In this new post I'm placing the same scritps with a few enhancements and the ability to add the computer to a pre-defined group.

Make sure you replace "YOUR GROUP GOES HERE" with the required group and the LDAPs with your own OU structure.

#Gets computer, model and type

$computer = (Get-WmiObject -Class Win32_ComputerSystem).name
$type = Get-WmiObject -Class Win32_SystemEnclosure | Select-Object -ExpandProperty ChassisTypes
$serial = (Get-WmiObject -Class Win32_SystemEnclosure | % {$_.serialnumber}).length

#Search the AD for the computer

$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(cn=$computer)"
$result = $search.FindOne()

#Converts the result to the required format

$computerToMove = [ADSI]$result.path
$computerToAdd = $result.GetDirectoryEntry().path

#Search the AD for the group

$search.Filter = "(cn=YOUR GROUP GOES HERE)"
$result = $search.FindOne()
$group = [ADSI]$result.path

#Move computer to required OU

Try{

if($type -eq 9 -or $type -eq 10){
$computerToMove.psbase.Moveto([ADSI]LDAP://OU=LAPTOPS,OU=COMPUTERS,DC=LAB,DC=COM)
$group.psbase.Invoke("Add",$computerToAdd)}

elseif($type -eq 1 -or ($type -eq 3 -and $serial -gt 20)){
$computerToMove.psbase.Moveto([ADSI]"LDAP://OU=VDI,OU=Computers,DC=LAB,DC=COM")}

else{
$computerToMove.psbase.Moveto([ADSI]"LDAP://OU=Desktops,OU=Computers,DC=LAB,DC=COM")}}

Catch{$error > C:\error.txt}


1 comment:

  1. Great Script TY, I have used it as a base for another script.

    ReplyDelete