Active Directory对象的Import-CSV已存在错误

时间:2015-09-03 13:55:17

标签: powershell csv active-directory

我创建了一个PowerShell脚本,用于从CSV文件导入新的AD用户。代码是:

package x.y does not exist

该脚本适用于CSV中大约一半的条目。对于其他人我得到错误:

Import-Module ActiveDirectory
$Users = Import-Csv -Delimiter "," -Path "C:\temp\kindergarten.csv"
$Password = 000
foreach ($User in $Users) {
    $Password = $Password + 1
    $OU = "OU=KCenter,OU=Students,OU=District Users New,DC=,DC=k12,DC=ny,DC=us"
    $UserFirstname = $User.FirstName
    $UserLastname = $User.LastName
    $DetailedName = $UserFirstname + " " + $UserLastname
    $FirstLetterFirstname = $UserFirstname.substring(0,1)
    $SAMName = $FirstLetterFirstname + $UserLastname
    $UserPrincipalName = $SAMName + "@student.pobschools.org"
    $Description = "Kindergarteners K-Center"


    New-ADUser -Name $DetailedName -SamAccountName $SAMName -UserPrincipalName $UserPrincipalName -DisplayName     
    $SAMName -GivenName $UserFirstname -Surname $UserLastname -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) 
    -Enabled $false -Description $Description -EmailAddress $UserPrincipalName -CannotChangePassword $true -ChangePasswordAtLogon $false -Path $OU
    }

如果我搜索用户,则会收到错误,因为没有结果。我不确定为什么它会像现有的那样回归。任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

阅读您的评论我认为这可能会对您有所帮助:

$VerbosePreference = 'Continue'

$Users = Import-Csv -Delimiter "," -Path "C:\temp\kindergarten.csv"
$Password = 000
foreach ($User in $Users) {

    $Password = $Password + 1
    $SamAccountName = $User.FirstName[0] + $User.LastName

    if ($U = Get-ADUser -Filter {SamAccountName -eq $SamAccountName}) {
        Write-Verbose "SamAccountName $($SamAccountName) already present"

        if ($U.GivenName -eq $User.FirstName) {
            Write-Verbose "User firstname $($User.FirstName) already present in AD"
            Continue # to the next user
        }
        $SamAccountName = $User.FirstName[1] + $User.LastName
        Write-Verbose "New SamAccountName generated $($SamAccountName)"
    }

    $ADParams = @{
        Name                  = $UserFirstname + ' ' + $UserLastname
        SamAccountName        = $SamAccountName
        UserPrincipalName     = $SamAccountName + '@student.pobschools.org'
        DisplayName           = $SamAccountName
        GivenName             = $User.FirstName
        Surname               = $User.LastName
        AccountPassword       = (ConvertTo-SecureString $Password -AsPlainText -Force)
        Enabled               = $false
        Description           = 'Kindergarteners K-Center'
        EmailAddress          = $SamAccountName + '@student.pobschools.org'
        CannotChangePassword  = $true
        ChangePasswordAtLogon = $false
        Path                  = 'OU=KCenter,OU=Students,OU=District Users New,DC=,DC=k12,DC=ny,DC=us'
    }
    Write-Verbose "Create user $($SamAccountName)"
    New-ADUser @ADParams
}

Splatting是一种很好的技巧,可以使事情更具可读性。