原始Script:

###########################################################
#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':
        #<FirstLetterInitials><FirstFourLettersLastName> 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"

修改后Script:

###########################################################
#AUTHOR  : Marius / Hican - http://www.hican.nl - @hicannl 
#DATE    : 26-04-2012 
#EDIT    : 07-08-2014
#COMMENT : This script creates new Active Directory users,#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 + "\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 add-adgroup
{

    Param ([String]$group2,[String]$username)

                Try   { $exists = Get-adgroup -Identity $group2 }
                Catch { Write-Host "[ERROR]`t Group not found: $($group2)" }
                If($exists)
                {
                    Add-ADGroupMember -identity $group2 -Member $username
                    Write-Host "[INFO]`t Added User $username into Group: $($group2)"
                    "[INFO]`t Added User $username into Group: $($group2)" | Out-File $log -append
                }
}

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 ($_.UserName -eq "")
      {
        Write-Host "[ERROR]`t Please provide valid UserName Processing skipped for line $($i)`r`n"
        "[ERROR]`t Please provide valid UserName. Processing skipped for line $($i)`r`n" | Out-File $log -append
      }
      Else
      {
        # Set the target OU
        $OU = ""

        if ($_.TYPE.ToLower() -eq "user"){
            $OU = "OU=Users"
        }Elseif ($_.TYPE.ToLower() -eq "service"){
            $OU = "OU=Service Accounts"
        }

        if ($_.components.toupper()) {

        $components = $OU + ",OU="+ $_.components.toupper() + ",OU=WIN_DM"

        }else {

        $components = $OU +  ",OU=WIN_DM"

        }

        $location = $components + ",$($addn)"

        Write-Host $location -ForegroundColor Yellow

        # Create sAMAccountName according to this 'naming convention':
        # <FirstLetterInitials><FirstFourLettersLastName> for example
        # htehp
        $sam = $_.UserName.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 "P@ssw0rd1234" -force

          Try
          {
            Write-Host "[INFO]`t Creating user : $($sam)"
            "[INFO]`t Creating user : $($sam)" | Out-File $log -append
            New-ADUser $sam `
            -displayName $sam `
            -Description "Owner:DCO" `
            -UserPrincipalName ($sam + "@" + $dnsroot) `
            -AccountPassword $setpass `
            -ChangePasswordAtlogon $True `
            -Enabled $True #-PasswordNeverExpires $True
            Write-Host "[INFO]`t Created new user : $($sam)"
            "[INFO]`t Created new user : $($sam)" | Out-File $log -append

            $dn = (Get-ADUser $sam).distinguishedname
          }
          Catch
          {
            Write-Host "[ERROR]`t Oops 1,something went wrong: $($_.Exception.Message)`r`n"
          }

          Try
          {
              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
          }
          Catch
          {
            Write-Host "[ERROR]`t Oops 2,something went wrong: $($_.Exception.Message)`r`n"
          }       

          Try
          {
                #add group member
                $sag = "service account groups"

                if ($_.TYPE.ToLower() -eq "service"){
                    add-adgroup $sag $sam
                }

                $group = $_.group.ToLower()
                if (!($group -eq ""))
                {
                    add-adgroup $group $sam
                }

          }
          Catch
          {
            Write-Host "[ERROR]`t Oops 3,something went wrong: $($_.Exception.Message)`r`n"
          }
        }
        Else
        {
          Write-Host "[SKIP]`t User $($sam) already exists or returned an error!`r`n"
          "[SKIP]`t User $($sam) already exists or returned an error!" | Out-File $log -append
        }
      }

    $i++
  }
  "--------------------------------------------" + "`r`n" | Out-File $log -append
}

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

Create AD Users by Powershell的更多相关文章

  1. 关于h5中的fetch方法解读(小结)

    这篇文章主要介绍了关于h5中的fetch方法解读(小结),fetch身为H5中的一个新对象,他的诞生,是为了取代ajax的存在而出现,有兴趣的可以了解一下

  2. ios – 从Live Photo中提取视频部分

    有没有人想出如何从LivePhoto中提取视频部分?

  3. ios – 使用Swift的Lumberjack 2.0记录器

    我以前使用物镜C的Lumberjack记录器,我喜欢它.现在我开始学习Swift,我不能在那里使用我最喜欢的记录器.有人可以一步一步地写出我能做到的事吗?在Lumberjack2.0发布之前,我尝试在这里找到一些东西,但所有主题都是自定义包装器.我做了什么:>我用Cocoapods添加了Lumberjack;>我将“#import”添加到Bridging-Header文件中.我不知道接下来该怎么办?因为在ObjC中我有宏:staticconstintddLogLevel=LOG_LEVEL_INFO;el

  4. 如何在iOS 10上设置日志级别?

    换句话说,如果我在iOS上运行的代码就像这样:那么在Console.app中看到记录的消息需要做些什么呢?

  5. ios – Objective-C中的混合或多重继承?

    换句话说,是否可以创建一个可以从这两个子类继承的抽象类,然后只覆盖两者之间不同的方法?我到目前为止所知道的>我知道Objective-C不支持多重继承>我知道我可以使用Categories添加常用的方法,但是我不认为这会解决覆盖init方法或添加私有属性解决方法建立在Amin的答案上,这是怎么做的呢?

  6. 为什么Xcode 8(iOS 10)在控制台中打印[LogMessageLogging]

    为什么Xcode8打印[LogMessageLogging]在控制台中,当我调用地图视图时?任何人都可以提出一些建议吗?解决方法PrivacyTheunifiedloggingsystemconsidersdynamicstringsandcomplexdynamicobjectstobeprivate,anddoesnotcollectthemautomatically.Toensuretheprivacyofusers,itisrecommendedthatlogmessagesconsiststri

  7. ios – 从embedded.mobileprovision配置文件获取证书到期日期

    谁可以帮我进一步?

  8. ios – 在Swift 4中为os_log传递可变参数

    我正在尝试为Swift4/iOS11中的os_log编写一个方便的包装器,但是我已经遇到了传递可变参数的艰难战斗.基本上,我想编写一个如下所示的函数.不幸的是,我似乎无法弄清楚传递参数的神奇语法,并且在CVararg讨论的泥潭中有点迷失.(…这让我想念Python的splatting语法)解决方法我还没有找到解决方案,所以这个愚蠢的黑客:

  9. xcode – osx上的config.log是什么?它在哪里?

    任何人都可以解释’configure’是什么和做什么,一般可以找到config.log文件?

  10. api – HTTPS请求仅在iOS,Ionic 2上失败

    我有一个Ionic2应用程序,它调用SpringBootAPI将推送通知发送到其他设备.API使用HTTPS配置.APIPOST请求适用于除iOS之外的所有内容.我在服务器上的SSL证书是自签名的(可能就是这样吗?

随机推荐

  1. static – 在页面之间共享数据的最佳实践

    我想知道在UWP的页面之间发送像’selectedItem’等变量的最佳做法是什么?创建一个每个页面都知道的静态全局变量类是一个好主意吗?

  2. .net – 为Windows窗体控件提供百分比宽度/高度

    WindowsForm开发的新手,但在Web开发方面经验丰富.有没有办法为Windows窗体控件指定百分比宽度/高度,以便在用户调整窗口大小时扩展/缩小?当窗口调整大小时,可以编写代码来改变控件的宽度/高度,但我希望有更好的方法,比如在HTML/CSS中.在那儿?

  3. 使用Windows Azure查询表存储数据

    我需要使用特定帐户吗?>将应用程序部署到Azure服务后,如何查询数据?GoogleAppEngine有一个数据查看器/查询工具,Azure有类似的东西吗?>您可以看到的sqlExpressintance仅在开发结构中,并且一旦您表示没有等效,所以请小心使用它.>您可以尝试使用Linqpad查询表格.看看JamieThomson的thispost.

  4. windows – SetupDiGetClassDevs是否与文档中的设备实例ID一起使用?

    有没有更好的方法可以使用DBT_DEVICEARRIVAL事件中的数据获取设备的更多信息?您似乎必须指定DIGCF_ALLCLASSES标志以查找与给定设备实例ID匹配的所有类,或者指定ClassGuid并使用DIGCF_DEFAULT标志.这对我有用:带输出:

  5. Windows Live ID是OpenID提供商吗?

    不,WindowsLiveID不是OpenID提供商.他们使用专有协议.自从他们的“测试版”期结束以来,他们从未宣布计划继续它.

  6. 如果我在代码中进行了更改,是否需要重新安装Windows服务?

    我写了一个Windows服务并安装它.现在我对代码进行了一些更改并重新构建了解决方案.我还应该重新安装服务吗?不,只需停止它,替换文件,然后重新启动它.

  7. 带有双引号的字符串回显使用Windows批处理输出文件

    我正在尝试使用Windows批处理文件重写配置文件.我循环遍历文件的行并查找我想要用指定的新行替换的行.我有一个’函数’将行写入文件问题是%Text%是一个嵌入双引号的字符串.然后失败了.可能还有其他角色也会导致失败.如何才能使用配置文件中的所有文本?尝试将所有“在文本中替换为^”.^是转义字符,因此“将被视为常规字符你可以尝试以下方法:其他可能导致错误的字符是:

  8. .net – 将控制台应用程序转换为服务?

    我正在寻找不同的优势/劣势,将我们长期使用的控制台应用程序转换为Windows服务.我们为ActiveMQ使用了一个叫做java服务包装器的东西,我相信人们告诉我你可以用它包装任何东西.这并不是说你应该用它包装任何东西;我们遇到了这个问题.控制台应用程序是一个.NET控制台应用程序,默认情况下会将大量信息记录到控制台,尽管这是可配置的.任何推荐?我们应该在VisualStudio中将其重建为服务吗?我使用“-install”/“-uninstall”开关执行此操作.例如,seehere.

  9. windows – 捕获外部程序的STDOUT和STDERR *同时*它正在执行(Ruby)

    哦,我在Windows上:-(实际上,它比我想象的要简单,这看起来很完美:…是的,它适用于Windows!

  10. windows – 当我试图批量打印变量时,为什么我得到“Echo is on”

    我想要执行一个简单的批处理文件脚本:当我在XP中运行时,它给了我预期的输出,但是当我在Vista或Windows7中运行它时,我在尝试打印值时得到“EchoisOn”.以下是程序的输出:摆脱集合表达式中的空格.等号(=)的两侧可以并且应该没有空格BTW:我通常在@echo关闭的情况下启动所有批处理文件,并以@echo结束它们,所以我可以避免将代码与批处理文件的输出混合.它只是使您的批处理文件输出更好,更清洁.

返回
顶部