Powershell组合自定义对象的最有效方法

我正在解析一个网页,但很难组合成一个变量。我也在寻找最有效的方法来做到这一点。这是我到目前为止的代码。任何帮助表示赞赏。

   $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 

谢谢

回答

使用基于索引的循环(假设所有三个数组都有对应的元素和相同的元素计数):

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

注属性名称如何Time(E/T)被封闭在'...'-逐字字符串-而不是{...}-一个脚本块; 后者只是偶然工作,因为脚本块将[1]字符串化为它们的逐字内容(没有{})。


[1] 当使用[pscustomobject] @{ ... }语法糖时,哈希表 ( @{ ... })的键被隐式字符串化,因为对象的属性名称总是字符串。


以上是Powershell组合自定义对象的最有效方法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>