使用CSV在AD中创建批量用户

时间:2017-06-15 20:28:23

标签: powershell csv active-directory

我正在开发一个Power Shell脚本,该脚本将在Active Directory中创建批量用户。正如前一篇文章中所述,我对Power Shell来说还是比较新的,并希望在我开始使用任何东西之前保持安全。下面是脚本,其中一些是借来的。它将从Import-CSV cmdlet中记录的.csv中读取数据。理想情况下,这将创建用户并定义用户的全名,名字,姓氏,用户名,SAM名称,电子邮件,标题,描述和经理。它还会设置密码。

我很想知道以下脚本的反馈意见。如果您有任何疑问或需要任何其他信息,请与我们联系。

    Import-Module activedirectory

$ADUsers = Import-CSV C:\scripts\hourlyimport.csv

foreach ($User in $ADUsers)
{
    #read user data from each field in each row and assign the data to a variable as below

    $Username   = $User.username
    $Firstname  = $User.firstname
    $Lastname   = $User.lastname
    $Password   = $User.password
    $OU         = $User.ou
    $Title      = $User.title
    $Manager    = $User.manager

    #check to see if the user already exists in AD

    if (Get-ADUser -F {SamAccountName -eq $Username})
    {
         #if user does exist, give a warning

         Write-Warning "A user account with username $Username already exist in Active Directory. Say wha?!?"
    }
    else
    {
        #if user does not exist then proceed to create the new user account

        #account will be created in the OU provided by the $OU variable read from the CSV file

        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@thredup.com" `
        -Email "$Username@thredup.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Lastname, $Firstname" `
            -Path $OU `
        -Description "$Title" `
        -Title "$Title" `
        -Manager "$Manager" `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force)
    }
}

1 个答案:

答案 0 :(得分:1)

对我来说很好看。您与"的使用有些不一致,例如您不需要写-Title "$Title",在这种情况下您可以放弃"

你可以在这里用splatting做一些花哨的优化,减少作业,但由于它在很多读者中是一个非常未知的特征,我不会在这里找到它。

我缺少的一件事是错误处理。使用默认设置,脚本将在出现错误时打印出错误,但继续循环。这是有意的吗?通常通过在脚本开头设置$ErrorActionPreference来明确说明您的意图。