Thursday, June 18, 2015

Move AD computer with PowerShell Script

The Need

Be able to easily and rapidly move a computer from an OU to another.

The Problem

If you saw other examples on the web, you saw 2 reccurant things.
  1. You need to know the Distinguished Name of your destination OU. And it's like : OU=Laptop,OU=GothamOffice,DC=wayneindus,DC=local. And my example is not so long.
  2. Or you can create a CSV with the OU you want.
For me each solution are not good. So I figured to do it otherwise.

The Solution

I created a script to list all OU with certain names, the container object Computers and put it in an array with an index. So you can visually chose witch OU you want.

2 concerns :
  1. Your computer OU name needs to have a nomenclature.
  2. I think more the 100 OU, you do not like my script.

 <#  
   Move AD computer in an OU.   
   Easily move computer between OU without to know the exact path or have a CSV.  
   To use the function you need to have the ActiveDirectory Module load in your PowerShell.  
   Version 1.1  
   Script by Jeremie Lauzier - Network Administrator, 2015-06-11    
 #>  
     $computer = Read-Host "Enter the name of the computer to move"  
     # Grab all computer OU bases of the name of it and the default container Computers.  
     $listou = Get-ADObject -Filter `  
           '(ObjectClass -eq "organizationalUnit" -and Name -like "Desk*") -or (ObjectClass -eq "organizationalUnit" -and Name -like "Lap*") -or (ObjectClass -eq "container" -and Name -like "Computers")' `  
           |Select DistinguishedName -ExpandProperty DistinguishedName | Sort-Object DistinguishedName  
     # Create an array and an index of it.  
     $arrayou = for($i=0;$i-le $listou.length-1;$i++){"`[{0}] = {1}" -f $i,$listou[$i]}  
     # Current information for the computer.  
     $computerou = Get-ADComputer $computer | Select DistinguishedName -ExpandProperty DistinguishedName  
     Write-Output "Computer $computer is member of this OU : $computerou."  
     Write-Output ""  
     # Show the list of the OU.  
     Write-Output "This is the list with index of your OU"  
     $arrayou  
     $numb = (Read-Host "Please choose the number of the destination OU") -as [int]  
     if (($numb -eq $null) -or ($numb -gt $arrayou.LongLength))  
     {  
       $earry1 = $arrayou.Length -1  
       Write-Error "YOU ENTER A UNVALID NUMBER. ENTER A NUMBER BEWTWEEN 0 and $earry1"  
     }  
     else  
     {  
       # Move the computer.  
       Get-ADComputer $computer | Move-ADObject -TargetPath $listou[$numb]    
     }  
     # Show result  
     Write-Output "Result :"  
     Get-ADComputer $computer  
     pause  

You can easily transform the script in a Function.

Exemple :

Result of the script
Result of the execution of the script
I hope this help you. Be free to comment.
Thanks !

No comments:

Post a Comment