Remove line from txt file if -notmatch

Welcome Forums General PowerShell Q&A Remove line from txt file if -notmatch

This topic contains 1 reply, has 2 voices, and was last updated by

4 years ago.

  • Author
  • #23328

    Points: 17
    Rank: Member

    The first part of my script seems to work fine. I am generating a list of accounts using compare-object. I am having trouble with the foreach-object. I want to exclude the line from my results if it matches any value in my $AccountsToRemove variable. Any help on what I am doing wrong would be appreciated. Final1.txt is comma delimited, $AccountsToRemove is a list of usernames.

    $UserResultsPath1 = "c:\final1.txt"
    $UserResultsPath2 = "c:\final2.txt"

    $Compare1 = import-csv -Path $UserResultsPath1
    $Compare2 = import-csv -Path $UserResultsPath2

    $AccountsToRemove = Compare-Object $Compare1 $Compare2 -property SamAccountName `
    | where-object {$_.SideIndicator -eq '<='} |Select-Object -Property SamAccountName -ExpandProperty SamAccountName $file = New-Object System.IO.StreamReader -Arg $UserResultsPath1 while ($line = $file.ReadLine()) { $AccountsToRemove | ForEach-Object {$_ -notmatch $line} | out-file "c:\finalresults.txt" -append write-host $line } $file.close()

  • #23331

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    You should really omit -Property from Select-Object; -ExpandProperty is what you need.

    Also, -match and -notmatch are regular expression comparisons. Not knowing what your strings look like, that's something to be aware of. If you're testing for an exact string match, you use -eq or -neq.

    Finally, I think you're probably making this a lot harder on yourself. let's assume $AccountsToRemove is an array of strings like "DonJ","ChrisG","GregS". Let's assume your text file contains DonJ and GregS, with one name per line.

    $AccountsToRemove = Compare-Object $Compare1 $Compare2 -property SamAccountName `
    | where-object {$_.SideIndicator -eq '< ="} |
    Select-Object -ExpandProperty SamAccountName
    $lines = Get-Content $UserResultsPath1
    foreach ($account in $accountstoremove) {
      if ($account -in $lines) {
        # name was found in file

    -contains, -notcontains, -in, and -notin will probably work a lot faster to determine if Object A exists in Collection B.

The topic ‘Remove line from txt file if -notmatch’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort