如何在PowerShell中将多个对象导出到不同的CSV列

时间:2017-09-25 17:29:13

标签: powershell csv

我抓了一个网站,我真正想要的是拥有一个CSV文件,其中包含每个单独列中的已删除字符串。

$page = Invoke-WebRequest -Uri "SomeURL"

$obj  = $page.ParsedHtml.Body.GetElementsByTagName('SomeTag') |
        Where {$_.GetAttributeNode('class').Value -eq 'someValue'}
$obj1 = $page.ParsedHtml.Body.GetElementsByTagName('SomeAnotherTag') |
        Where {$_.GetAttributeNode('class').Value -eq 'someAnotherValue'}
$obj2 = $page.ParsedHtml.Body.GetElementsByTagName('yetAnotherTag') |
        Where {$_.getAttributeNode('class').Value -eq 'yetAnotherValue'}

$locations  = $obj.InnerText   
$locations1 = $obj1.InnerText
$locations2 = $obj2.InnerText

$toExport0 = $locations | Select-Object @{Name='locations';Expression={$_}}
$toExport1 = $locations1 | Select-Object @{Name='AnotherSetOflocations';Expression={$_}}
$toExport2 = $locations2 | Select-Object @{Name='YetAnotherSetOflocations';Expression={$_}}

$locations$locaitons1$locations2中的每一个都包含已删除的字符串。当我输出它们时,它是这样的:

word
another word
yet another word
.
.
.

我想要的输出是(将其导出为以列分隔的CSV文件):

locations,anotherSetOfLocations,YetAnotherSetOfLocations
word,...,...
another word,...,...
yet another word,...,...
.
.
.

1 个答案:

答案 0 :(得分:0)

在这些位中:

$toExport0 = $locations | select-object @{Name='locations'; Expression={$_}}

您正在创建三个单独的对象,但这些对象无法用于CSV创建。删除这些行,并在获得位置后立即执行所有操作。

你需要一个对象,上面有三个属性:

$toExport = [PSCustomObject]@{

    'locations'       = $locations
    'anotherSetOfLoc' = $locations2
    'locations3'      = $locations3

}

$toExport | Export-Csv out.csv -NoTypeInformation