Match and Remove Row from csv

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of H Man H Man 1 year, 9 months ago.

  • Author
    Posts
  • #28311
    Profile photo of H Man
    H Man
    Participant

    I am getting daily results i need to match and remove from a csv file.

    The code i am trying to use is deleting all the data

    i am trying to match the records based on the computername column (the $check variable also hasa computername property) find the computers in $check variable and remove them from the csv file

    $Check = Get-lmcompatibilitylevel -Session $s
    $records = Import-Csv $CSVFile
    Import-Csv $CSVFile `
    | ? { $Check.computername -notcontains $_."ComputerName" } `
    | Export-Csv $CSVFile -NoTypeInformation

    any help would be greatly appreciated

    thx

  • #28312
    Profile photo of Stephen Owen
    Stephen Owen
    Participant

    For situations like this, I would recommend that you provide us sample rows to work with, so that we can provide code to more accurately solve your problem. RUn something like the following:

    Get-lmcompatibilitylevel -Session $s | Select -first 50 | Export-Csv c:\pathto\File.csv

    And then sanitize it (remove your company data) and post it up on PasteBin or somewhere similar. We'll be happy to help, and it will be a lot easier to do so.

    I did try your code out, and I made the following files to do so. It worked!

    I just created the following file, check.csv

    ComputerName
    ------------
    ham         
    pig         
    bacon       
    pork   
    

    I then made another file called CSVFile.Csv

    ComputerName
    ------------
    ham         
    pig         
    bacon       
    pork        
    cat         
    dog         
    meow 
    

    When I run pretty much your same code, it successfully omits the items found in Check

    $Check = import-csv T:\Check.csv
    $records = Import-Csv T:\CSVFile.csv
    $records | ? { $Check.computername -notcontains $_."ComputerName" } 
       
    ComputerName
    ------------
    cat         
    dog         
    meow  
    
  • #28317
    Profile photo of Bob McCoy
    Bob McCoy
    Participant

    Just a quick style note. You don't have to (and probably shouldn't) use the line continuation character (`) at the end of the line when you're still piping. The back tick is notoriously disliked because it's hard to see. The following is the preferred method.

    Import-Csv $CSVFile  |
        where  { $Check.computername -notcontains $_."ComputerName" }  | 
        Export-Csv $CSVFile -NoTypeInformation
    

    Also, please limit the use of single-character aliases when sharing/posting code you want others to review.

  • #28391
    Profile photo of H Man
    H Man
    Participant

    Thanks for the input guys 🙂

You must be logged in to reply to this topic.