设为首页 收藏本站
查看: 2228|回复: 0

Create AD Users by Powershell

[复制链接]

尚未签到

发表于 2018-9-15 10:52:45 | 显示全部楼层 |阅读模式
###########################################################  #AUTHOR  : Marius / Hican - http://www.hican.nl - @hicannl
  #DATE    : 26-04-2012
  #EDIT    : 07-08-2014
  #COMMENT : This script creates new Active Directory users,
  #including different kind of properties, based
  #on an input_create_ad_users.csv.
  #VERSION : 1.3
  ###########################################################
  #CHANGELOG
  #Version 1.2: 15-04-2014 - Changed the code for better
  #- Added better Error Handling and Reporting.
  #- Changed input file with more logical headers.
  #- Added functionality for account Enabled,
  #PasswordNeverExpires, ProfilePath, ScriptPath,
  #HomeDirectory and HomeDrive
  #- Added the option to move every user to a different OU.
  #Version 1.3: 08-07-2014
  #- Added functionality for ProxyAddresses
  #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.csv"
  $log      = $path + "\create_ad_users.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")
  {
  If (($_.GivenName -eq "") -Or ($_.LastName -eq "") -Or ($_.Initials -eq ""))
  {
  Write-Host "[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n"
  "[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n" | Out-File $log -append
  }
  Else
  {
  #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 = "EN"
  }
  #Replace dots / points (.) in names, because AD will error when a
  #name ends with a dot (and it looks cleaner as well)
  $replace = $_.Lastname.Replace(".","")
  If($replace.length -lt 4)
  {
  $lastname = $replace
  }
  Else
  {
  $lastname = $replace.substring(0,4)
  }
  #Create sAMAccountName according to this 'naming convention':
  # for example
  #htehp
  $sam = $_.Initials.substring(0,1).ToLower() + $lastname.ToLower()
  Try   { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
  Catch { }
  If(!$exists)
  {
  #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 : $($sam)"
  "[INFO]`t Creating user : $($sam)" | Out-File $log -append
  New-ADUser $sam -GivenName $_.GivenName -Initials $_.Initials `
  -Surname $_.LastName -DisplayName ($_.LastName + "," + $_.Initials + " " + $_.GivenName) `
  -Office $_.OfficeName -Description $_.Description -EmailAddress $_.Mail `
  -StreetAddress $_.StreetAddress -City $_.City -State $_.State `
  -PostalCode $_.PostalCode -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
  -Company $_.Company -Department $_.Department -EmployeeID $_.EmployeeID `
  -Title $_.Title -OfficePhone $_.Phone -AccountPassword $setpass -Manager $_.Manager `
  -profilePath $_.ProfilePath -scriptPath $_.ScriptPath -homeDirectory $_.HomeDirectory `
  -homeDrive $_.homeDrive -Enabled $enabled -PasswordNeverExpires $expires
  Write-Host "[INFO]`t Created new user : $($sam)"
  "[INFO]`t Created new user : $($sam)" | Out-File $log -append
  $dn = (Get-ADUser $sam).DistinguishedName
  #Set an ExtensionAttribute
  If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
  {
  $ext = [ADSI]"LDAP://$dn"
  $ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
  Try   { $ext.SetInfo() }
  Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
  }
  #Set ProxyAdresses
  Try { $dn | Set-ADUser -Add @{proxyAddresses = ($_.ProxyAddresses -split ";")} -ErrorAction Stop }
  Catch { Write-Host "[ERROR]`t Couldn't set the ProxyAddresses Attributes : $($_.Exception.Message)" }
  #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 $sam moved to target OU : $($location)"
  "[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
  }
  Else
  {
  Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!"
  "[ERROR]`t Targeted OU 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 $sam).DistinguishedName
  Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
  Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n"
  "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
  }
  Catch
  {
  Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
  }
  }
  Else
  {
  Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
  "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
  }
  }
  }
  Else
  {
  Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
  "[SKIP]`t User ($($_.GivenName) $($_.LastName)) 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"


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-583314-1-1.html 上篇帖子: PowerShell 在线教程 下篇帖子: 输入、过滤和输出——PowerShell三分钟(八)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表