none
for-each on text file stops processing after condition is met RRS feed

  • Question

  • I have a text file with over 2000 records, when I run the below code I only get the result of the first line, which

    does meet the first condition of the if statement and my results are:

    hello

    true

    --thats it, it reads the first line of the file and then stops because the condition is met

    code:

            

    foreach ($record in (get-content "c:\test2.txt")) {
    $checkname = $record.loginname
    write-host 'hello'

        if ($checkname -eq $null) 
            {
                    return $true

             }
          if ($checkname -is [String] -and $checkname -eq [String]::Empty) 
          {
         write-host 'here2' 
         return $true
          } 
          if ($checkname -is [DBNull] -or $checkname -is [System.Management.Automation.Language.NullString]) 
          {
            return $true
           write-host 'here3'
          }
             }


    I know it is reading the file, because if I take out the if statements, I get thousands of hello as I would expect

    foreach ($record in (get-content "c:\temp\test.txt")) {
    
    
    
    $checkname = $record.loginname
    write-host 'hello'
    
        if ($checkname -eq $null) 
            {
            write-host 'here'
            return $true
            
             }
          if ($checkname -is [String] -and $checkname -eq [String]::Empty) 
          {
         write-host 'here2' 
         return $true
          } 
          if ($checkname -is [DBNull] -or $checkname -is [System.Management.Automation.Language.NullString]) 
          {
            return $true
           write-host 'here3'
          }
        write-host 'hello2'
          }


    • Edited by Kspencer66 Wednesday, September 25, 2019 1:36 PM
    Tuesday, September 24, 2019 7:34 PM

All replies

  • Please fix your post and format your code as code: How to Use the Code Feature in a TechNet Forum Post.

    Where do you define $checkname? From a text file you cannot create object with attributes like $record.loginname.


    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Tuesday, September 24, 2019 7:39 PM
    Tuesday, September 24, 2019 7:38 PM
  • ok sorry. Submitted code correctly.

    $record is the line in the text file as defined in the foreach

    loginname is a column header in the text file


    Wednesday, September 25, 2019 1:39 PM
  • Hmmm ... ok, that sounds like your text file is actually a csv file. If yes you should treat it as such and use Import-CSV instead of Get-Content.

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Wednesday, September 25, 2019 3:59 PM