PowerShell 通过来自 CSV 的 UPN 将 AD 用户添加到 AD 组

PowerShell Add AD users to AD group by UPN from CSV

Import-CSV "C:\Temp\jacktest.csv" | Foreach-Object {
  $aduser = Get-ADUser -Filter "UPN-eq '$($_.UPN)'"
  if( $aduser ) {
    Write-Output "Adding user $($aduser.SamAccountName) to groupname"
    Add-ADGroupMember -Identity JackTest -Members $aduser
  } else {
    Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
  }
}

我收到以下错误:

转录开始,输出文件为C:\Temp\Add-ADUsers.log Get-ADUser:无法识别搜索过滤器 在 line:19 char:15

检查 csv 文件,您似乎没有使用默认分隔符。 如果是这样,请将参数 -delimiter 添加到 import-csv cmdlet。 例如制表符分隔符:

Import-CSV "C:\Temp\jacktest.csv" -delimiter "`t"

此回答旨在帮助您排查问题,以便我们了解您的 CSV 可能出现的问题。

请注意,此代码假定您的 CSV 文件以逗号分隔,并且 CSV 文件中有一列名称为“UserPrincipalName”。

$usersToAdd = foreach($line in Import-CSV "C:\Temp\jacktest.csv")
{
    if([string]::IsNullOrWhiteSpace($line.UserPrincipalName))
    {
        Write-Warning 'Empty UserPrincialName Value:'
        Write-Warning $line
        continue
    }

    $aduser = Get-ADUser -Filter "UserPrincipalName -eq '$($line.UserPrincipalName)'"
    if(-not $aduser)
    {
        Write-Warning "$($line.UserPrincipalName) could not be found."
        continue
    }

    $aduser
}

if($usersToAdd)
{
    Write-Host 'The following users will be added to the Group'
    $usersToAdd.UserPrincialName
    try
    {
        Add-ADGroupMember -Identity JackTest -Members $usersToAdd
    }
    catch
    {
        Write-Warning $_.Exception.Message
    }
}