Search code examples
arrayspowershelllineskip

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


I would like to skip a line in the $array if there are certain words in the $array (current line)

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

Solution

  • The main code issue is that you can't put your if statement inside the [PSCustomObject] constructor.

    You're also trying to compare previous results when you use $array, you should use $_ for everything which needs to reference the current line.

    you can also make life much easier by:

    • constructing a proper regex instead of using multiple -match statement
    • negating the if statement to avoid using continue

    The 'fixed' code would look something like this:

    $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()
            }
        }
    }