【问题标题】:Creating Bulk Users in AD With CSV使用 CSV 在 AD 中创建批量用户
【发布时间】:2017-06-15 20:28:23
【问题描述】:

我正在编写一个将在 Active Directory 中创建批量用户的 Power Shell 脚本。如前一篇文章所述,我对 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)
    }
}

【问题讨论】:

    标签: powershell csv active-directory


    【解决方案1】:

    对我来说看起来不错。你对"的使用有些不一致,比如你不需要写-Title "$Title",这种情况下可以不用"

    您可能可以在这里使用splatting 进行一些花哨的优化,减少分配,但由于它在许多读者中是一个非常陌生的功能,我不会在这里使用它。

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

    【讨论】:

    • 知道了。所以我只需要在合并数据时引用引号,例如添加@domain.com 或创建“完整”名称?
    • 是的,将"与变量一起使用是PowerShell使用string.Format的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多