代码之家  ›  专栏  ›  技术社区  ›  Wiktor

Powershel-从循环中提取到csv

  •  1
  • Wiktor  · 技术社区  · 5 年前

    $Output = @()
    foreach($emailproxy in $emailproxies)
    {
    if($emailproxy.Mail -like "*com" -or $emailproxy.Mail -like "*org"){ Write-Host $emailproxy.Mail} 
     $Output = New-Object -TypeName PSObject -Property @{
            Mail = $emailproxy.Mail
        } | Select-Object Mail
    }
    
    $Output | Export-Csv C:\TempDownloads\results.csv
    

    我只有一份简历。。为什么?

    2 回复  |  直到 5 年前
        1
  •  2
  •   stackoverflowusrone Esailija    5 年前

    对于循环中的每个迭代,您将直接将值分配(覆盖)给 $Output 变量,而不是将值添加到数组中。

    在for循环中,需要替换 $Output = $Output += .

    • $Output = <new value> ->分配 <new value> $输出 被覆盖并丢失。

    • $Output += <new value> 相当于 $Output = $Output + <new value> <新价值> 以及 首先合并,然后分配给 $输出

        2
  •  0
  •   Wasif    5 年前

    这是因为您每次都要对变量$output进行过度校正。您需要使用add member将属性附加到psobject

    Output = New-Object -TypeName Psobject 
    foreach($emailproxy in $emailproxies) { if($emailproxy.Mail -like "*com" -or $emailproxy.Mail -like "*org"){ Write-Host $emailproxy.Mail} 
    $Output | Add-Member -MemberType NoteProperty -Name "Mail" -Value $_.mail
    }
     $Output | Export-Csv "filepath"