Powershell Most efficient way to combine customobject

Viewed 54

I'm parsing a webpage, but having difficulty combining into one variable. I'm looking for the most efficient way to do so as well. This is code I have so far. Any help is appreciated.

   $WebResponse = Invoke-WebRequest -Uri "https://finviz.com/news.ashx"

$title = ($WebResponse.AllElements | Where {$_.class -match 'nn-tab-link'}).innertext
$time = ($WebResponse.AllElements | Where {$_.class -match 'nn-date'}).innertext
$link = ($WebResponse.AllElements | Where {$_.class -match 'nn-tab-link'}).href


$r =  {
    [PSCustomObject]@{
        {Time(E/T)} = $time
        Headline = $title
        Link = $link
    }
}
 $R 

Thanks

1 Answers

Use an index-based loop (which assumes that all three arrays have corresponding elements and the same element count):

$objects = foreach ($i in 0..($title.Count-1)) {
  [pscustomobject] @{
    'Time(E/T)' = $time[$i]
    Headline = $title[$i]
    Link = $link[$i]
  }
}

Note how property name Time(E/T) is enclosed in '...' - a verbatim string - rather than in {...} - a script block; the latter only works accidentally, because script blocks stringify[1] to their verbatim content (without the { and }).


[1] When using the [pscustomobject] @{ ... } syntactic sugar, the keys of the hashtable (@{ ... }) are implicitly stringified, given that objects' property names are invariably strings.

Related