Powershell AD:根据名称的CSV输入导出特定字段的CSV?

时间:2014-01-15 20:58:26

标签: powershell active-directory powershell-v2.0 export-to-csv import-from-csv

我需要传入一个用户列表,并使用姓名,SamAccountName,电子邮件返回CSV

我的输入CSV如下:

"John Doe"
"Jane Doe"

这是我正在使用的当前代码。我不确定问题是什么。用户实际上确实存在于指定的“DC”...

Import-Module ActiveDirectory
Function Get-ADUsersDetailsCSV
{
    [CmdletBinding()]
    Param
    (
    [Parameter(Mandatory=$True,Position=1)]
    [String]$InCSV,

    [Parameter(Mandatory=$True)]
    [String]$OutCSV
    )

If($InCSV)
{
    If(Test-Path -Path $InCSV)
    {
        $USERS = Import-CSV $InCSV -Header Name
        $USERS|Foreach{Get-ADUser $_.Name -Properties * |Select Name, SAMAccountName, mail}|Export-CSV -Path $OutCSV

    } #End Test that the files exist

    Else
    {
        Write-Warning "Cannot find path '$InCSV' because it does not exist."
    }


} #End Ensure Input and Output files were provided

} #End Function Get-UsersDetailsCSV

这是错误:

Get-ADUser : Cannot find an object with identity: 'John Doe' under: 'DC=blah,DC=com'.
At U:\data\GetADUserInfo PS Script\GetADUsersDetailsCSV.psm1:19 char:28
+             $USERS|Foreach{Get-ADUser $_.Name -Properties * |Select Name, SAMAcc ...
+                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ObjectNotFound: (Name:ADUser) [Get-ADUser], ADIdentityNotFoundException
+ FullyQualifiedErrorId : Cannot find an object with identity: 'John Doe' under: 'DC=blah,DC=com'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser

1 个答案:

答案 0 :(得分:1)

根据您的上述反馈,我将对此答案进行更改。但是,由于您使用Get-ADUser对象获取名称和电子邮件属性,因此无需运行Get-ADUser两次。

$user = Get-ADuser -Filer { Name -eq $Name }

此外,您还可以将不同的对象组合在一起。试试这个,看看你得到了什么

$ExportCSVPath = "C:\Exportedcsv.csv"
$users = (Import-Csv -Path $CsvFilePath) |  
    % {Get-ADUser -Filter { Name -eq $_.DisplayName } | 
        Select -ExpandProperty SamAccountName, mail } |
            Export-Csv $ExportCSVPath