Get-ADUser无法找到所有用户

时间:2014-10-04 22:37:45

标签: excel powershell active-directory

我一次只能从Excel电子表格中读取用户列表。一旦我得到它,我试图在Active Directory中获取与我从Excel文件中提取的用户名匹配的用户对象。不幸的是,它获得了第一个用户,但之后每个用户都说它无法找到它们。这就是我正在做的事情:

do
{    
    # Get the user's login name
    $userPrincipalName = $objWorksheet.Cells.Item($intRow, 1).Value()

    # Get the user description
    $description = $objWorksheet.Cells.Item($intRow, 2).Value()

    $intRow++

    $user = Get-ADUser -Filter "userPrincipalName -eq '$userPrincipalName'" -Properties Description

    if ($user)
    {
        if (!($user.Description))
        {
            $user | Set-ADUser -Description $description
            Write-Host "User" $userPrincipalName "was altered."

            $num_of_users_altered++
        }

        else
        {
            Write-Host "User" $userPrincipalName "already has a description."
        }
    }

    else
    {
        Write-Host "User" $userPrincipalName "was not found."
        $num_of_users_not_altered++
    }


} 
while ($objWorksheet.Cells.Item($intRow, 1).Value() -ne $null)

现在,第一个用户(找到的用户)与其他用户位于不同的OU中。我已经尝试从电子表格中删除该用户,看看他们是否在不同的OU中的问题,但它没有找到任何一个。我可能做错了什么想法?

1 个答案:

答案 0 :(得分:0)

你的循环看起来应该有效。

  • 您确定所有用户都拥有UPN(user1@mydomain.com),而不是samAccountName(user1)吗?
  • 如果您手动运行Get-ADUser -Filter "userPrincipalName -eq '$userPrincipalName'" -Properties Description(使用"未找到" -message?
  • 中的一个值替换$userPrincipalName,您会得到任何结果吗?
  • 如果你使用它($userPrincipalName = $objWorksheet.Cells.Item($intRow, 1).Value().Trim())会发生什么?
  • 将文件转换为CSV会有所不同吗?就个人而言,我总是建议在PowerShell中使用CSV文件。 CSV文件很容易使用。

样品:

Import-CSV -Path "c:\mycsvfile.csv" | ForEach-Object {
    #Modify to match your column names
    $upn = $_.userPrincipalName.Trim()
    $desc = $_.description.Trim()

    $user = Get-ADUser -Filter "userPrincipalName -eq '$upn'" -Properties Description

    if ($user)
    {
        if (!($user.Description))
        {
            $user | Set-ADUser -Description $desc
            Write-Host "User" $upn "was altered."

            $num_of_users_altered++
        }

        else
        {
            Write-Host "User" $upn "already has a description."
        }
    }

    else
    {
        Write-Host "User" $upn "was not found."
        $num_of_users_not_altered++
    }
}
相关问题