如何将PowerShell结果导出到csv

如何将PowerShell结果导出到csv,powershell,foreach,export-csv,Powershell,Foreach,Export Csv,我想导出在ForEach对象中已过滤的内容。问题是我无法导出过滤后的数据 我尝试了以下方法: $getTapes.rows |导出Csv C:\\123\\123456.txt,但这已导出所有信息,不带过滤器 $getTapes = Invoke-RestMethod -Method GET -ContentType $content -Uri $Uri -Headers @{'Authorization' = $Authorization} $today = Get-Date $getTape

我想导出在ForEach对象中已过滤的内容。问题是我无法导出过滤后的数据

我尝试了以下方法: $getTapes.rows |导出Csv C:\\123\\123456.txt,但这已导出所有信息,不带过滤器

$getTapes = Invoke-RestMethod -Method GET -ContentType $content -Uri $Uri -Headers @{'Authorization' = $Authorization}
$today = Get-Date
$getTapes.rows | ForEach-Object {
    $tape = $_;    
    if ( $tape.custom_fields.Ueberschreibschutz.value -ge $today ) {
        Write-Host "Treffer ID=" $tape.asset_tag " Name=" $tape.name " SNR=" $tape.serial " Mediensatz=" $tape.custom_fields.Mediensatz.value
    }
}
$getTapes.rows |export-Csv C:\\123\\123456.txt
我期望:

Treffer ID= 1  Name= 12  SNR= 12345  Mediensatz= M 
Treffer ID= 2  Name= 32  SNR= 54321  Mediensatz= W

您不应该使用写主机来收集数据。这只是为了在屏幕上输出像素。相反,您应该创建一个自定义对象,您可以在以后使用它。。。像这样:

    $Result = $getTapes.rows | ForEach-Object { 
    if ( $_.custom_fields.Ueberschreibschutz.value -ge $today ) {
        [PSCustomObject]@{
            TrefferID  = $_.asset_tag
            Name       = $_.name
            SNR        = $_.serial
            Mediensatz = $_.custom_fields.Mediensatz.value
        }
    }
}

$Result | Export-Csv -Path C:\123\123456.csv -NoTypeInformation
Write host除了在控制台中显示结果外,什么都不做,因此它不会修改或删除$getTapes.rows中不需要的内容。 相反,您可以定义一个变量$result,并使用Foreach对象迭代$getTapes.rows,如果结果满足if条件,则添加该结果

试试这个:

$getTapes = Invoke-RestMethod -Method GET -ContentType $content -Uri $Uri -Headers @{'Authorization' = $Authorization}
$today = Get-Date
$getTapes.rows | ForEach-Object -begin {$result = "" } {
    $tape = $_;    
    if ( $tape.custom_fields.Ueberschreibschutz.value -ge $today ) {
        $result += "Treffer ID= $($tape.asset_tag) Name= $($tape.name) SNR= $($tape.serial) Mediensatz= $($tape.custom_fields.Mediensatz.value)`n"
    }
} -end {$result | export-Csv C:\123\123456.txt}