Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell Foreach不从数组中跳过值_Powershell_Foreach_Skip - Fatal编程技术网

Powershell Foreach不从数组中跳过值

Powershell Foreach不从数组中跳过值,powershell,foreach,skip,Powershell,Foreach,Skip,我正在尝试编写一个脚本来下载网站信息。我可以下载信息,但我似乎无法让过滤工作。我有一系列要跳过的值存储在$TakeOut中,但它无法识别if-eq$TakeOut中的值。我必须为每个值写一行 我想知道的是,是否有一种方法可以使用$value,因为随着时间的推移,会有大量的值需要跳过 这是可行的,但从长远来看并不实用 if ($R.innerText -eq "Home") {Continue} 像这样的东西会更好 if ($R.innerText -eq $TakeOut) {Continue

我正在尝试编写一个脚本来下载网站信息。我可以下载信息,但我似乎无法让过滤工作。我有一系列要跳过的值存储在
$TakeOut
中,但它无法识别if
-eq$TakeOut
中的值。我必须为每个值写一行

我想知道的是,是否有一种方法可以使用
$value
,因为随着时间的推移,会有大量的值需要跳过

这是可行的,但从长远来看并不实用

if ($R.innerText -eq "Home") {Continue}
像这样的东西会更好

if ($R.innerText -eq $TakeOut) {Continue}
这是我的代码示例

#List of values to skip
$TakeOut = @()
$TakeOut = (
"Help",
"Home",
"News",
"Sports",
"Terms of use",
"Travel",
"Video",
"Weather"
)

#Retrieve website information
$Results = ((Invoke-WebRequest -Uri "https://www.msn.com/en-ca/").Links)

#Filter and format to new table of values
$objects = @()
foreach($R in $Results) {
   if ($R.innerText -eq $TakeOut) {Continue}
   $objects += New-Object -Type PSObject -Prop @{'InnerText'= $R.InnerText;'href'=$R.href;'Title'=$R.href.split('/')[4]}
}

#output to file
$objects  | ConvertTo-HTML -As Table -Fragment | Out-String >> $list_F

不能有意义地将数组用作
-eq
操作的RHS(数组将被隐式字符串化,这将无法按预期工作)

PowerShell具有运算符
-包含
-in
,用于测试数组中某个值的成员身份(基于每个元素使用
-eq
,请参阅背景);因此:

 if ($R.innerText -in $TakeOut) {Continue}

通常,您的代码可以简化(PSv3+语法):

  • 请注意缺少
    @(…)
    ,这对于数组文本来说是不需要的

  • 使用
    +=
    在循环中构建数组速度慢(而且冗长);只需使用
    foreach
    语句作为表达式,它将循环体的输出作为数组返回

  • [pscustomobject]@{…}
    是用于构造自定义对象的PSv3+语法糖;除了比
    新对象
    调用更快之外,它还具有保留属性顺序的额外优势

您可以将整个过程编写为单个管道:

#Retrieve website information
(Invoke-WebRequest -Uri "https://www.msn.com/en-ca/").Links | ForEach-Object {
   #Filter and format to new table of values
   if ($_.innerText -in $TakeOut) {return}
   [pscustomobject @{
      InnerText = $_.InnerText
      href = $_.href
      Title = $_.href.split('/')[4]
   }
} | ConvertTo-HTML -As Table -Fragment >> $list_F

请注意,需要使用
return
而不是
continue
来继续下一个输入。

很高兴听到这个消息,@Woody。
#Retrieve website information
(Invoke-WebRequest -Uri "https://www.msn.com/en-ca/").Links | ForEach-Object {
   #Filter and format to new table of values
   if ($_.innerText -in $TakeOut) {return}
   [pscustomobject @{
      InnerText = $_.InnerText
      href = $_.href
      Title = $_.href.split('/')[4]
   }
} | ConvertTo-HTML -As Table -Fragment >> $list_F