在数组中执行自定义对象时跳过 powershell 行

skip line powershell when you are doing a custum object in an array

如果 $array 中有某些单词(当前行),我想跳过 $array 中的一行

 Get-Content -path $inDirFile | foreach{ # Read test.txt file and handle each line with foreach
                $array += [PSCustomObject]@{
                    If ([string]::IsNullOrWhitespace($array) -Or $array -Match "=" -Or $array -Match "PAGE" -Or $array -Match "MENUITM" -Or $array -Match "----" -Or $array -Match "USER") {
                    continue
                    }
                    else{
                    Field1 = $_.substring(1,12).Trim();
                    Field2 = $_.substring(13,11).Trim();
                    Field3 = $_.substring(25,2).Trim();
                    Field4 = $_.substring(28,2).Trim();
                    Field5 = $_.substring(31,2).Trim();
                    Field6 = $_.substring(34,2).Trim();
                    Field7 = $_.substring(41); # Substring from index 41 to the end of line
                    }
                }
}   

主要代码问题是您不能将 if 语句放在 [PSCustomObject] 构造函数中。

当您使用 $array 时,您还试图比较以前的结果,对于需要引用当前行的所有内容,您应该使用 $_

您还可以通过以下方式让生活变得更轻松:

  • 构建正确的正则表达式而不是使用多个 -match 语句
  • 否定 if 语句以避免使用 continue

'fixed' 代码看起来像这样:

$array = @()
Get-Content $inDirFile | Foreach-Object {
    if (-not ( [string]::IsNullOrWhiteSpace($_) -or $_ -match "=|PAGE|MENUITM|----|USER" ) ){
        $array += [PSCustomObject]@{
            Field1 = $_.Substring(1, 3).Trim()
            Field2 = $_.Substring(5, 3).Trim()
            Field3 = $_.Substring(10,3).Trim()
        }
    }
}