批量导入AD用户

powershell脚本

<########################################################### 
# Modified From Marius / Hican - http://www.hican.nl - @hicannl  
# Original Script From https://gallery.technet.microsoft.com/scriptcenter/PowerShell-Create-Active-7e6a3978
# Excel file / Input CSV structure
# Implement | Name | Mail | Country | Company | Department | Title | MobilePhone | Password | PasswordNeverExpires | Enabled | TargetOU
# yes/no | YourName | [email protected] | China | Tech.Ltd | IT | Engineer | 12345678911 | plain-text-password | true/false | true/false | OU=xxx,OU=yyy
############################################################>
# ERROR REPORTING ALL
Set-StrictMode -Version latest

#----------------------------------------------------------
# LOAD ASSEMBLIES AND MODULES
#----------------------------------------------------------
Try
{
  Import-Module ActiveDirectory -ErrorAction Stop
}
Catch
{
  Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
  Exit 1
}

#----------------------------------------------------------
#STATIC VARIABLES
#----------------------------------------------------------
$path     = Split-Path -parent $MyInvocation.MyCommand.Definition
$newpath  = $path + "\import_create_ad_users.v2.csv"
$log      = $path + "\create_ad_users.v2.log"
$date     = Get-Date
$addn     = (Get-ADDomain).DistinguishedName
$dnsroot  = (Get-ADDomain).DNSRoot
$i        = 1

#----------------------------------------------------------
#START FUNCTIONS
#----------------------------------------------------------
Function Start-Commands
{
  Create-Users
}

Function Create-Users
{
  "Processing started (on " + $date + "): " | Out-File $log -append
  "--------------------------------------------" | Out-File $log -append
  Import-CSV $newpath | ForEach-Object {
    If (($_.Implement.ToLower()) -eq "yes")
    {
      # Set the target OU
      $location = $_.TargetOU + ",$($addn)"
      
      # Set the Enabled and PasswordNeverExpires properties
      If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
      If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }
      
      # A check for the country, because those were full names and need 
      # to be land codes in order for AD to accept them. I used Netherlands 
      # as example
      If($_.Country -eq "Netherlands")
      {
        $_.Country = "NL"
      }
      Else
      {
        $_.Country = "CN"
      }
      # Create sAMAccountName according to mail address:
      #  for example
      # htehp
      $sam = $_.Mail.split('@')[0].ToLower()
      # Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
      # Catch { }
      Try { $exists = @(dsquery user -samid $sam).count }
      Catch { }
      # If(!$exists)
      If($exists -eq 0)
      {
        # Set all variables according to the table names in the Excel 
        # sheet / import CSV. The names can differ in every project, but 
        # if the names change, make sure to change it below as well.
        $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
      
        Try
        {
          Write-Host "[INFO]`t Creating user : $($_.Name)"
          "[INFO]`t Creating user : $($_.Name)" | Out-File $log -append
          New-ADUser $_.Name -SAMAccountName $sam -DisplayName $_.Name `
          -givenName $_.Name -EmailAddress $_.Mail -MobilePhone $_.MobilePhone `
          -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
          -Company $_.Company -Department $_.Department `
          -Title $_.Title -AccountPassword $setpass `
          -Enabled $enabled -PasswordNeverExpires $expires
          Write-Host "[INFO]`t Created new user : $($_.Name)"
          "[INFO]`t Created new user : $($_.Name)" | Out-File $log -append
          
          $dn = (Get-ADUser $sam).DistinguishedName
          
          # Move the user to the OU ($location) you set above. If you don't
          # want to move the user(s) and just create them in the global Users
          # OU, comment the string below
          If ([adsi]::Exists("LDAP://$($location)"))
          {
            Move-ADObject -Identity $dn -TargetPath $location
            Write-Host "[INFO]`t User $_.Name($sam) moved to target OU : $($location)"
            "[INFO]`t User $_.Name($sam) moved to target OU : $($location)" | Out-File $log -append
          }
          Else
          {
            Write-Host "[ERROR]`t Targeted OU $($location) couldn't be found. Newly created user wasn't moved!"
            "[ERROR]`t Targeted OU $($location) couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
          }
          
          # Rename the object to a good looking name (otherwise you see
          # the 'ugly' shortened sAMAccountNames as a name in AD. This
          # can't be set right away (as sAMAccountName) due to the 20
          # character restriction
          # $newdn = (Get-ADUser $_.Name).DistinguishedName
          # Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
          # Write-Host "[INFO]`t Renamed $($_.Name) to $($_.GivenName) $($_.LastName)`r`n"
          # "[INFO]`t Renamed $($_.Name) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
        }
        Catch
        {
          Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
        }
      }
      Elseif($exists -eq 1)
      {
        Try
        {
          Write-Host "[INFO]`t User $($_.Name) already exists and modifying!`r`n"
          "[INFO]`t Modifying user : $($_.Name)" | Out-File $log -append
          Set-ADUser -Identity $sam -DisplayName $_.Name `
          -givenName $_.Name -EmailAddress $_.Mail -MobilePhone $_.MobilePhone `
          -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
          -Company $_.Company -Department $_.Department `
          -Title $_.Title -Enabled $enabled -PasswordNeverExpires $expires
          Write-Host "[INFO]`t Modified user : $($_.Name)"
          "[INFO]`t User $($_.Name) already exists and modified!" | Out-File $log -append
        }
        Catch
        {
          Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
        }
      }
      else
      {
        Write-Host "[SKIP]`t User $($_.Name) returned an error!`r`n"
        "[SKIP]`t User $($_.Name) returned an error!" | Out-File $log -append
      }
    }
    Else
    {
      Write-Host "[SKIP]`t User ($($_.Name)) will be skipped for processing!`r`n"
      "[SKIP]`t User ($($_.Name)) will be skipped for processing!" | Out-File $log -append
    }
    $i++
  }
  "--------------------------------------------" + "`r`n" | Out-File $log -append
}

Write-Host "STARTED SCRIPT`r`n"
Start-Commands
Write-Host "STOPPED SCRIPT"

你可能感兴趣的:(批量导入AD用户)