【问题标题】:How can I pull usernames from AD using powershell and the email addresses如何使用 powershell 和电子邮件地址从 AD 中提取用户名
【发布时间】:2022-01-15 09:28:10
【问题描述】:

我可以通过搜索电子邮件地址从 AD 中提取单个用户名,但我想从 CSV 中提取多个电子邮件地址并将它们记录到输出文件中。我知道我需要在这里扩大搜索范围:mail -eq 'john.smith@example.com' 使用诸如 -like 或变量之类的内容,但我很难找到解决方案。

代码:

$InputFile = 'C:\emailaddresses.csv'
$Outputfile = 'C:\usernames.csv'

Import-CSV -Path $InputFile 
      | ForEach-Object { Get-ADUser -Filter { mail -eq 'john.smith@example.com' } | select SamAccountName } 
      | Export-Csv $OutputFile -NoTypeInformation

【问题讨论】:

  • 您当前的脚本有什么问题?
  • 我正在尝试制作一个导入大量电子邮件地址的列表,并使用 get-ADuser 从 AD 中提取用户名并将其导出到 csv 文件。当前脚本仅提取我指定的单个地址的用户名。
  • 您的emailaddresses.csv 文件应包含列名的标题。假设标题名为Email。然后您的查询变为Get-ADUser -Filter "mail -eq '$($_.Email)'"Foreach-Object 将每个流水线对象处理为$_$PSItem$() 是必要的,因为您的过滤器字符串对内部的所有内容执行字符串扩展,将替换 $_,然后将 .Email 附加到它。
  • @AdminOfThings 这有帮助,当然让我朝着正确的方向前进。现在,对于列表中的每个地址,我都会收到以下错误。 Error parsing query: 'mail 'john.smith@example.com'' Error Message: 'syntax error' at position: '6'. At line:1 char:48
  • 您的过滤器中没有比较运算符。试试-Filter "mail -eq '$($_.Email)'"

标签: powershell export-to-csv userid email-address get-aduser


【解决方案1】:

答案可能是间隔和 AD 调用是一个痛苦的注意 $Email

$InputFile = 'C:\emailaddresses.csv'
#assumption that header for the file above is email
$Outputfile = 'C:\usernames.csv'

Import-CSV -Path $InputFile | ForEach-Object { 
    $email = $null
    $email = $_.email
    Get-ADUser -Filter { mail -eq $email } | Select-Object SamAccountName } | Export-Csv $OutputFile -NoTypeInformation

我假设标题是第一个 csv 中的电子邮件,我不确定您是想要 -eq 还是 -like,但我在这里的回答会让您到达那里。

我在我的机器上测试了它,它可以工作。

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 2021-08-15
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2010-12-20
    相关资源
    最近更新 更多