powershell - 如何在Powershell中将输入文件中的值添加为导出的输出文件中的列?

标签 powershell scripting active-directory

我有一个包含以下数据的输入文件(input.txt)。以下数据作为联系人保存在我的域中。我的任务是在我的域中为这些联系人标识相应的邮件ID。

 abcd@otherdomain.com
 efgh@otherdomain.com
 ijkl@otherdomain.com

以下是我为完成任务而编写的powershell脚本。这些联系人的目标地址将是我的域电子邮件ID。但是这里的问题是,在导出时,我还需要将输入数据附加到我的结果中。
Write-Host "Reading Input File.. "
$users=""
ForEach ($contact in $(Get-Content 'Input.txt')) 
{
    $DomainId = Get-ADObject -Filter  {(mail -eq $contact) -and (ObjectClass -eq "Contact")} -Properties * | Select targetAddress
    $DomainId = $DomainId.targetAddress.remove(0,5) 
    $users+= (Get-AdUser -Filter {Mail -eq $DomainId} -Properties * | Select Mail)      
}
Write-Host "Exporting to CSV.."   
$users | Export-CSV -Path 'output.csv' -NoTypeInformation

下面是当前输出(output.csv)
Mail;
ab@mydomain.com;
ef@mydomain.com;
ij@mydomain.com;

但是预期的输出是
Mail;InputId;
ab@mydomain.com;abcd@otherdomain.com;
ef@mydomain.com;efgh@otherdomain.com;
ij@mydomain.com;ijkl@otherdomain.com;

是否有可能获得预期的输出。如果是这样,请协助。在此先感谢您的支持。

最佳答案

未经测试,但类似的方法可能有效:

Write-Host "Reading Input File.. "
$users = foreach ($contact in (Get-Content 'Input.txt')) 
{
    $DomainId = Get-ADObject -Filter {
                        (mail -eq $contact) -and (ObjectClass -eq "Contact")
                    } -Properties * | Select-Object -ExpandProperty targetAddress

    $DomainId = $DomainId.Remove(0,5)
    $Mail = (Get-AdUser -Filter {Mail -eq $DomainId} -Properties Mail).Mail

    [PSCustomObject]@{
        InputId = $DomainId
        Mail = $Mail
    } 
}

Write-Host "Exporting to CSV.."   
$users | Export-CSV -Path 'output.csv' -NoTypeInformation

您希望PSCustomObjects进入Export-CSV,每列一个属性。而且它们很容易通过从哈希表进行强制转换来构建,而不是使用大量的Add-Member。

关于powershell - 如何在Powershell中将输入文件中的值添加为导出的输出文件中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249049/

相关文章:

Powershell 模块存储用户设置的位置

powershell - 在 Powershell 中生成具有 X.509 证书签名的 JWT

linux - 在 Linux 中查找多个文件并重命名它们

linux - su下如何运行sudo?

azure - postman : "You do not have permission to view this directory or page"带有不记名 token

image - 在 PowerShell 中提取 EXIF 数据的简便方法?

json - 女士powershell : how to handle json- objects?

lua - {LUA} 如何在脚本中触发另一个脚本?

iis - 直通身份验证 - IIS 虚拟目录

php - 如何在 PHP 中使用 NT 身份验证连接?