【问题标题】:How to add the value in input file as a column in exported output file in powershell?如何将输入文件中的值添加为powershell中导出的输出文件中的列?
【发布时间】:2017-03-08 00:55:58
【问题描述】:

我有一个包含以下数据的输入文件(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;

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

【问题讨论】:

    标签: powershell scripting active-directory


    【解决方案1】:

    未经测试,但类似这样的方法可以工作:

    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。

    【讨论】:

      猜你喜欢
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2014-02-05
      • 2018-07-26
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多