批量创建新联系人并添加到发行版

Creating New Contacts In Bulk AND adding to distros

我有一个使用 PS 和 CSV 创建批量外部联系人的脚本。我想对此进行调整,不仅可以创建联系人,还可以将联系人添加到任何指定的发行版。

foreach($contact in (import-csv c:\users\ME\desktop\contactstest.csv)){
$properties = @{
    type            = 'Contact'
    name            = $contact.firstname + ", " + $contact.lastname
    OtherAttributes = @{'mail' = "$($contact.email)"}
    Path            = "OU=External Contacts,DC=Company,DC=org"
}

New-ADObject @properties

}

如果我有包含以下列的 CSV。这可行吗?

Firstname/lastname/email/Group

CSV 位于 DC 的桌​​面上。


CSV 示例

第一个,最后一个,电子邮件,群组

billy,bob,bb@aol.com,emailist1

我现在明白第一次出了什么问题了。
我的意思是让您 New-ADObject @properties 替换为我的代码块。由于您也保留了它,因此代码尝试创建联系人两次,导致错误消息并跳过将联系人添加到组的部分。

如果您的 CSV 如下所示:

first,last,email,group
billy,bob,bb@aol.com,emailist1
jane,doe,jd@somewhereintheworld.com,emaillist1;emaillist5

注意第二个联系人要添加到两个组中,用分号分隔;

这里是完整的代码:

foreach ($contact in (import-csv c:\users\ME\desktop\contactstest.csv)) {
    # create a hash table for splatting the parameters to New-ADObject
    $properties = @{
        type            = 'Contact'
        name            = $contact.firstname + ", " + $contact.lastname
        OtherAttributes = @{'mail' = "$($contact.email)"}
        Path            = "OU=External Contacts,DC=Company,DC=org"
    }
    # create the contact and capture the resulting object
    $newContact = New-ADObject @properties -PassThru -ErrorAction SilentlyContinue
    if ($newContact) {
        # if success, add this contact to the group(s)
        $contact.Group -split ';' | ForEach-Object {
            Add-ADGroupMember -Identity $_ -Members $newContact
        }    
    }
    else {
        Write-Warning "Could not create contact $($contact.lastname)"
    }
}

P.S。您还可以将 PassThru 和 ErrorAction 参数包含到散列哈希中:

$properties = @{
    type            = 'Contact'
    name            = $contact.firstname + ", " + $contact.lastname
    OtherAttributes = @{'mail' = "$($contact.email)"}
    Path            = "OU=External Contacts,DC=Company,DC=org"
    PassThru        = $true
    ErrorAction     = 'SilentlyContinue'
}