Search code examples
powershellserveractive-directory

Bulk hostname movement to desired OU


I am having a script for moving hostnames to particular OU.

gc .\list.txt |ForEach-Object { Get-ADComputer $_ | move-adobject -targetpath "" }

In above script actually am having 150 hostnames and needs to move different different ou. How we can do that.

example.

masuadfl01  --   move to  masu/branches/laptops
masufgd002  --   move to  masu/branches/desktops
abdufghd001  --  move to  abdu/branches/desktops

Like above everything should move automatically correct OU. How we can create a script like that.

If it is desktop last before digit D will be there. For laptop L will be.


Solution

  • A bit more overhead here, but you can use regex for this

    First, set the regex

    # will match a d,l,D or L character before the digit
    [regex]$regex = "[dlDL](?=\d)"
    

    Then you can loop through your list of hostnames

    Get-Content -Path .\list.txt | ForEach-Object {
        
        # check if the hostname matches the regex
        $match = $regex.Match($_)
        
        # get the desired OU, first 4 characters
        $desiredOU = $_.Substring(0,4)
    
        If($match.Success){
            # if client is L -> move to laptops
            If($match.Value.ToUpper() -eq "L"){
                Write-Host "$_ is a laptop" -ForegroundColor Green
                Get-ADComputer $_ | Move-ADObject -TargetPath "OU=laptops,OU=branches,OU=$desiredOU,DC=Contoso,DC=com"
            # if client is D -> move to desktops
            }Elseif($match.Value.ToUpper() -eq "D"){
                Write-Host "$_ is a desktop" -ForegroundColor Green
                Get-ADComputer $_ | Move-ADObject -TargetPath "OU=desktops,OU=branches,OU=$desiredOU,DC=Contoso,DC=com"
            }Else{
                Write-Host "$_ not a laptop nor desktop" -ForegroundColor Red
            }
        }Else{
            Write-Host "$_ not a laptop nor desktop" -ForegroundColor Red
        }
    }