为什么我不能在powershell中提取实际给定的名称属性?

时间:2017-05-26 15:25:07

标签: powershell

$Results = @()
$Users = Import-CSV C:\Filter\test1.CSV -Header First,Last,Email
Foreach($User in $Users){
    $UserProps = get-aduser -Filter "GivenName -eq '$($user.GivenName)' -and Surname -eq '$($user.Surname)'" -Properties GivenName,Surname,EmailAddress,Department
    $Results += New-Object PSObject -Property @{
        FirstName = $User.GivenName
        LastName = $User.Surname
        EmailAddress = $User.EmailAddress
        Department = $UserProps.Department}
}
$Results 

这是test1.CSV 3列包括:

第一封电子邮件

Westley XXX email@email.gov

Dave XXX email@email.gov

Gareth XXX email@email.gov

Paul XXX email@email.gov

我想要它做的是运行CSV并从PowerShell中提取活动帐户信息,但是我不认为这样做,因为我的名字应该打印出其他内容

我应该打印出DavidJ作为测试,因为我编辑了我的帐户,而是打印Dave作为我的名字,它是如何在电子表格(CSV)中。

get-aduser:无法识别搜索过滤器 在线:2字符:18 + $ UserProps = get-aduser -Filter“GivenName -eq'$($ user.GivenName)' - and Sur ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo:NotSpecified:(:) [Get-ADUser],ADException     + FullyQualifiedErrorId:ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser

预期产出:

EmailAddress FirstName Department LastName

------------ --------- ---------- --------

westley@email.gov westley mydepartment hislastnamefromAD

david@email.gov davidj(来自AD)mydepartment mylastnamefromAD

gareth@gmail.gov gareth mydepartment hislastnamefromAD

paul@gmail.com paul mydepartment hislastnamefromAD

2 个答案:

答案 0 :(得分:1)

在你的例子中:

$Results = @()
$Users = Import-CSV C:\Filter\test1.CSV -Header First,Last,Email
Foreach($User in $Users){
    $UserProps = get-aduser -Filter "GivenName -eq '$($user.GivenName)' -and Surname -eq '$($user.Surname)'" -Properties GivenName,Surname,EmailAddress,Department
    $Results += New-Object PSObject -Property @{
        FirstName = $User.GivenName
        LastName = $User.Surname
        EmailAddress = $User.EmailAddress
        Department = $UserProps.Department}
}
$Results 

您正在使用$ User.GivenName而不是$ UserProps。 $ User变量仅使用csv文件中提供的内容。您需要将为自定义对象提供的值更改为使用$ UserProps形式的Active Directory返回。

FirstName = $UserProps.GivenName

答案 1 :(得分:0)

导入的对象有.First。和.Last属性,但您尝试在.GivenName .SurName参数中使用名为Get-ADUser-Filter的属性。

此外,作为Jason's answer points out,您尝试从导入的CSV $User变量填充结果对象,而不是从查询的AD $UserProps变量填充。

这些问题已在您的代码的更简单,更惯用的重新制定中得到修复:

$Results = Import-CSV C:\Filter\test1.CSV -Header First,Last,Email |
  Get-ADUser -Filter "GivenName -eq '$($_.First)' -and Surname -eq '$($_.Last)'" -Properties GivenName,Surname,EmailAddress,Department |
    Select-Object @{ l = 'FirstName'; e = 'GivenName' }, 
                  @{ l = 'LastName'; e = 'Surname' }, 
                  EmailAddress, 
                  Department

# Output results.
$Results