首页 > 解决方案 > 使用某些字段从 AD 导出用户

问题描述

在以某种方式格式化的 csv 中获取某些信息时,我遇到了一些困难。

我需要按此顺序输入以下字段:

Email   First Name  Last Name   Group   Location    
Department  Manager First Name  Manager Last Name   
Manager Email   Employee Number Job Title   Business Unit   Cost Center

其中大部分我可以轻松完成,但我不确定如何处理经理信息。因为要拉经理,它只是拉 DN。谁能帮我一个这个?

Get-ADUser -Filter * -Properties * 
    | Select-Object mail, GivenName, SN, department, 
    | export-csv -path c:\temp\userexport.csv`

标签: powershellactive-directory

解决方案


默认情况下,Get-ADUser 已返回以下属性: DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName

对于其他人,您需要使用该-Properties参数。

虽然不熟悉属性的 LDAP 名称Group,Business UnitCost Center,但我认为它们可能分别命名为defaultGroup,oubusinessCategory
请随时纠正我。

$userProps = 'EmailAddress','defaultGroup','Office','Department','Manager','EmployeeNumber','Title','ou','businessCategory'
Get-ADUser -Filter * -Properties $userProps | ForEach-Object {
    try {
        # this may fail if the user has its 'Manager' property not set. In that case we enter the catch block
        $mgr = Get-ADUser -Identity $_.Manager -Properties EmailAddress -ErrorAction Stop
    }
    catch { <# do nothing here, we'll test if there is a manager later #> }
    # output an object with the desired properties
    [PsCustomObject]@{
        'Email'              = $_.EmailAddress
        'First Name'         = $_.GivenName
        'Last Name'          = $_.Surname
        'Group'              = $_.defaultGroup
        'Location'           = $_.Office
        'Department'         = $_.Department
        'Manager First Name' = if ($mgr) { $mgr.GivenName } else { 'Not available' }
        'Manager Last Name'  = if ($mgr) { $mgr.Surname } else { 'Not available' }
        'Manager Email'      = if ($mgr) { $mgr.EmailAddress } else { 'Not available' }
        'Employee Number'    = $_.EmployeeNumber
        'Job Title'          = $_.Title
        'Business Unit'      = $_.ou
        'Cost Center'        = $_.businessCategory
    }
} | Export-Csv -Path 'c:\temp\userexport.csv' -NoTypeInformation

推荐阅读