Home > Software engineering >  Powershell Select-String Problem with variable
Powershell Select-String Problem with variable

Time:04-28

I have a CSV list of numbers that I would like to use Select-String to return the name of the file that the string is in.

When I do this

$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList) 
        {
            $orderFilename = $FileList | Select-String -Pattern "3505343956" | Select Filename,Pattern
            $orderFilename
        }

It gives me a response, I realize it is in a loop, but it gives me a response (albeit many times). This is what I would like.

Order# 199450619.pdf.txt 3505343956 Order# 199450619.pdf.txt 3505343956

But, when I run this:

$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList) 
        {
            $orderFilename = $FileList | Select-String -Pattern "$invoice" | Select Filename,Pattern
            $orderFilename
        }

or this

$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList) 
        {
            $orderFilename = $FileList | Select-String -Pattern $invoice | Select Filename,Pattern
            $orderFilename
        }

I get nothing in return.

I know there is data in $invoice because if I just ouput $invoice, I get all the invoice numbers that are in the CSV.

What am I doing wrong?

CodePudding user response:

Since $InvoiceList contains the output from a Import-Csv call, it contains custom objects with properties named for the CSV columns, not strings.

Therefore, you must explicitly access the property that contains the invoice number (as a string) in order to use it as search pattern with Select-String.

Assuming that the property / column name of interest is InvoiceNum (adjust as needed):

Foreach ($invoice in $InvoiceList.InvoiceNum) { # Note the .InvoiceNum
  $FileList | Select-String -Pattern $invoice | Select Filename,Pattern
}

Note:

  • Even though $InvoiceList contains an array of objects, PowerShell allows you to access a property that only exists on the elements of the array (.InvoiceNum here), and get the elements' property values as a result - this convenient feature is called member-access enumeration.

However, note that Select-String's -Pattern parameter accepts an array of search patterns, so you can shorten your command as follows, which also improves performance:

$FileList |
  Select-String -Pattern (Import-Csv C:\invoiceList.csv).InvoiceNum |
    Select-Object Filename,Pattern
  • Related