Monday, November 10, 2014

PowerShell: Add Computer to Domain directly to OU

Here's a PowerShell script to add computers to the Domain to a specific OU (Organizational Unit) and allows you to select the OU Location. I did not use the AD modules as they are not pre-installed on most desktops, even though it would of been much easier to write with them.
### -----------------------------------------------------------------
### Written by Matt Brown
### - http://universitytechnology.blogspot.com/
### PowerShell script to search OU Structure and add computer to domain
###
### -----------------------------------------------------------------

Param(
 $user = $(Get-Credential -Credential "domain\user"), # Prompts user for credentials
 $filter = "(objectClass=organizationalUnit)",  # Do not change
 $ouLocatoin = "LDAP://OU=Departments,DC=domain,DC=com", # Starting Organizational Unit
 $mydomain = "domain.com",    # FQDN of Domain
 $whatif = "-WhatIf"      # change to "" to actually run
)

#--------------------------------------------------------------------
Function GetSecurePass ($SecurePassword) {
  $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SecurePassword)
  $password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
  [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
  $password
}   
#--------------------------------------------------------------------
Function AddTabs($mystring,[int]$numtabs=5) {
 for([int]$len = (([string]$mystring).length / 8.9); $len -lt $numtabs; $len++) { $mystring += "`t" }
 return $mystring
}
#--------------------------------------------------------------------
Function SelectOU($dn,$up) {

 Clear-Host
 Write-Host "### -----------------------------------------------------------------" -ForegroundColor Green
 Write-Host "### Select OU and Add Computer to Domain                             " -ForegroundColor Green
 Write-Host "### Written by Matt Brown                                            " -ForegroundColor Green
 Write-Host "###  - http://universitytechnology.blogspot.com/                     " -ForegroundColor Green
 Write-Host "### PowerShell v.2 (Windows 7 / Server 2008 R2)                      " -ForegroundColor Green
 Write-Host "### -----------------------------------------------------------------" -ForegroundColor Green
 Write-Host "`nThe Number in the Select column adds the computer to the OU, where the List column will list Sub-OU's of the OU." -ForegroundColor Green
 Write-Host $dn
 Write-Host $up
 Write-Host "`n"
 Write-Host ("List Of " + (([string]$dn).split("/"))[2]) -ForegroundColor Yellow
 Write-Host " Select  List`tOU"
 Write-Host " ----------------------------------------------------"
 Write-Host "   0`t  L0   <- Up a Level"
 #$ou = Get-ADOrganizationalUnit -SearchBase $dn -SearchScope OneLevel -Filter 'Name -like "*"'
 
 $auth = [System.DirectoryServices.AuthenticationTypes]::FastBind
 $de = New-Object System.DirectoryServices.DirectoryEntry($dn,$user.UserName,(GetSecurePass $user.Password),$auth)
 $ds = New-Object system.DirectoryServices.DirectorySearcher($de,$filter)
 $ds.SearchScope = "OneLevel"
 $ou=($ds.Findall()) | Sort-Object -Property Name
 $sel = $null
 $selectList = @("0","L0","C")
 
 for($x=1; $ou.count -ge $x; $x++) {
  # output line, decide if it needs to be in yellow or white
  $selectList += $x
  $selectList += ("L"+$x)
  $outname = (AddTabs ($ou[$x-1].Properties['name']))
  $lineout = ("   " + $x + "`t  " + ("L"+$x) + "`t" + $outname)
  if($x % 2 -eq 0) {
   Write-Host $lineout -BackgroundColor White -ForegroundColor Black
  } else { 
   Write-Host $lineout -BackgroundColor Gray -ForegroundColor Black
  }
 }
 Write-Host "   C`t  C    -- Cancel & Exit"
 Write-Host "`n"
 while($selectList -notcontains $sel) {
  $sel = Read-Host "   Select OU or List Sub-OUs"
 }
 
 ## Figure out what the user selected
 if ( $sel[0] -eq "L") {
  ## Users Selected List Mode
  $y = ($sel.split("Ll")[1])
  if([int]$y -eq 0) { 
   $newup = ("LDAP://" + ($up -replace (($up -split ",")[0] + ",")))
   SelectOU $up $newup
  } else { 
   SelectOU $ou[$y-1].Properties['adspath'] $dn 
  }
 } elseif ($sel -eq "c") {
  ## User Selected Cancel
  return $false
 } else {
  ## User Selected the OU
  if([int]$sel -eq 0) {
   return ([string]$dn).split("//")[2] 
  } elseif([int]$sel -le [int]$ou.count)  { 
   return $ou[$sel-1].Properties['distinguishedname']
  } else { 
   SelectOU $dn $up 
  }
  
 }
} 
#--------------------------------------------------------------------

#--------------------------------------------------------------------
## Main
#--------------------------------------------------------------------

## Select / View OU
while($ou = (SelectOU $ouLocatoin $ouLocatoin)) {
 ## Add to Domain
 Write-Host ("  Will add computer (" + $env:computername + ") to:") -ForegroundColor Yellow
 Write-Host ("    " + $ou + "`n") -ForegroundColor Green
 $continue = Read-Host "  Continue (y | n)"
 if($continue -eq "y") {
  ## Now Add the Computer to the Domain
  add-computer -domainname $mydomain -OUPath $ou -Credential $user $whatif
  break
 } 
}

No comments:

Post a Comment