我有一個 CSV 數字串列,我想使用 Select-String 回傳字串所在檔案的名稱。
當我這樣做時
$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList)
{
$orderFilename = $FileList | Select-String -Pattern "3505343956" | Select Filename,Pattern
$orderFilename
}
它給了我一個回應,我意識到它在一個回圈中,但它給了我一個回應(盡管很多次)。這就是我想要的。
訂單號 199450619.pdf.txt 3505343956 訂單號 199450619.pdf.txt 3505343956
但是,當我運行這個時:
$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList)
{
$orderFilename = $FileList | Select-String -Pattern "$invoice" | Select Filename,Pattern
$orderFilename
}
或這個
$InvoiceList = Import-CSV "C:\invoiceList.csv"
Foreach ($invoice in $InvoiceList)
{
$orderFilename = $FileList | Select-String -Pattern $invoice | Select Filename,Pattern
$orderFilename
}
我什么也得不到。
我知道 $invoice 中有資料,因為如果我只輸出 $invoice,我會得到 CSV 中的所有發票編號。
我究竟做錯了什么?
uj5u.com熱心網友回復:
由于$InvoiceList包含Import-Csv呼叫的輸出,因此它包含具有以 CSV 列命名的屬性的自定義物件,而不是字串。
因此,您必須顯式訪問包含發票編號(作為字串)的屬性,才能將其用作搜索模式Select-String。
假設感興趣的屬性/列名稱是InvoiceNum(根據需要調整):
Foreach ($invoice in $InvoiceList.InvoiceNum) { # Note the .InvoiceNum
$FileList | Select-String -Pattern $invoice | Select Filename,Pattern
}
筆記:
- 即使
$InvoiceList包含物件陣列,PowerShell 也允許您訪問僅存在于陣列元素.InvoiceNum上的屬性(此處),并獲取元素的屬性值作為結果 - 這個方便的功能稱為成員訪問列舉。
但是,請注意Select-String'-Pattern引數接受搜索模式陣列,因此您可以按如下方式縮短命令,這也可以提高性能:
$FileList |
Select-String -Pattern (Import-Csv C:\invoiceList.csv).InvoiceNum |
Select-Object Filename,Pattern
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/466216.html
