简体   繁体   中英

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.

$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. 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):

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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