none
PowerShell - Display lines based on character position. RRS feed

  • Question

  • The List.txt file contains:

    00.0001 - Product 1
    Manufacturer
    Country of origin
    Distributor
    unity
    Amount
    Purchase Date
    Due date
    00.0002 - Product 2
    Manufacturer
    Country of origin
    Distributor
    unity
    Amount
    Purchase Date
    Due date
    00.0003 - Product 3
    Manufacturer
    Country of origin
    Distributor
    unity
    Amount
    Purchase Date
    Due date


    I want to display only the lines that have a dot in the third character, like this:

    00.0001 - Product 1
    00.0002 - Product 2
    00.0003 - Product 3

    I tried

    $x = Get-Content C:\Teste\List.txt
    for($i=0;$i -lt $x.Count;$i++){
        if ($x.Substring(2,1) = '.'){
    	$x.Substring(2,1)
    }
    }

     
    Saturday, July 4, 2020 1:16 AM

Answers

  • If $x is an array then you'll have to use a subscript to reference an individual element. E.g.:

        if ($x[$i].substring -eq '.'){ etc. }

    Or do it this way, without subscripting at all:

    Get-Content C:\Teste\List.txt |
        ForEach-Object {
            if ($_.substring(2,1) -eq '.'){
                $_
            }
        }

    Or this way, without the looping and substring:

    Get-Content C:\Teste\List.txt |
        Select-String -Pattern "^..\."


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)



    Saturday, July 4, 2020 2:47 AM

All replies

  • In PowerShell we use -eq to test.  The equal sign is for assignment only.

    help about_Comparison_Operators


    \_(ツ)_/

    Saturday, July 4, 2020 1:31 AM
    Moderator
  • If $x is an array then you'll have to use a subscript to reference an individual element. E.g.:

        if ($x[$i].substring -eq '.'){ etc. }

    Or do it this way, without subscripting at all:

    Get-Content C:\Teste\List.txt |
        ForEach-Object {
            if ($_.substring(2,1) -eq '.'){
                $_
            }
        }

    Or this way, without the looping and substring:

    Get-Content C:\Teste\List.txt |
        Select-String -Pattern "^..\."


    --- Rich Matheisen MCSE&I, Exchange Ex-MVP (16 years)



    Saturday, July 4, 2020 2:47 AM