简体   繁体   English

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

[英]How can I export multiple objects to different CSV columns in PowerShell

I scraped one website and what I really want is to have a CSV file that contains the scraped strings each in a separate column. 我抓取了一个网站,我真正想要的是拥有一个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={$_}}

Each of $locations , $locaitons1 , and $locations2 contains scraped strings. $locations$locaitons1$locations2中的每个包含刮擦的字符串。 When I output them it's like this: 当我输出它们时,就像这样:

word
another word
yet another word
.
.
.

The output that I want is (exporting it to CSV file separated in columns): 我想要的输出是(将其导出到以列分隔的CSV文件中):

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

In these bits: 在这些位中:

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

You are creating three separate objects, and that won't work for the CSV creation. 您正在创建三个单独的对象,这些对象不适用于CSV创建。 Remove those lines, and do it all at once after you have the locations. 删除这些行,找到位置后立即执行所有操作。

You need one object, with three properties on it: 您需要一个具有三个属性的对象:

$toExport = [PSCustomObject]@{

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

}

$toExport | Export-Csv out.csv -NoTypeInformation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM