Search code examples
sqlpowershellfilterresultset

Powershell: compare and filter SQL-Reply/Array with filecontent


I have a preset SQL-query and the result set stored in an array that I'd like to filter for further processing with documentIDs from a separate file content (*.txt)
The result set contains a documentID and a dateStored attribute. The seapare file contains document IDs on each line.

    # compare filecontent and sql reply
if(![string]::IsNullOrEmpty($filecontent)){
    "INFO:`tReporting File is not empty." | Write-Logfile
    if($sql_reply.Length -gt 0) {
        $missing_in_db = [string[]](Compare-Object $filecontent $sql_reply.documentId | Where {$_.sideindicator -eq "<="} | % {$_.inputobject})   
        echo Missing: `t $missing_in_db

        $exist_in_db = [string[]](Compare-Object $filecontent $sql_reply.documentId  -IncludeEqual -ExcludeDifferent | Where {$_.sideindicator -eq "=="} | % {$_.inputobject})   
        echo Exists: `t$exist_in_db

        #Need adivce/help with this part:
        $filteredResultSet =  $sql_reply | where{$sql_reply.documentID in $exist_in_db}
     }
 }

Either I need the $exist_in_db array to have all the $sql_reply attributes or to filter the original $sql_reply with the matching document IDs out from $filecontent. Any tips on how to achieve that?

Edit: Thanks for the hint MBo! This is how I set in place working as intended:

$mailbody += "<table>
                <tr>
                    <td><b>DocumentID</b></td>
                    <td><b>ItemName</b></td>
                    <td><b>ImportDate</b></td>
                </tr>"

 foreach($e in $exist_in_db) {
    $mailbody += "<tr>
                    <td>" + $sql_reply.Where({$_.documentID -eq $e}).documentId + "</td>
                    <td>" + $sql_reply.Where({$_.documentID -eq $e}).itemname + "</td>
                    <td>" + $sql_reply.Where({$_.documentID -eq $e}).datestored.toString("dd.MM.yyyy HH:mm:ss") + "</td>
                  </tr>"
 }

Solution

  • e.g loop throught the exist in db and find the corresponding object in the sql reply like:

        $sql_reply = ConvertFrom-Csv @'
        Name,Article,Size
        David,TShirt,M
        Eduard,Trouwsers,S
        Marc,Trouwsers,L
        Reto,Trouwsers,XS
        '@
    
        $exist_in_db=@("S","L","M")
    
        foreach ($s in $exist_in_db)
        {
            $sql_reply.Where({$_.Size -eq $s}).Name
            $sql_reply.Where({$_.Size -eq $s}).Article
        }