PowerShell | Get-Content & Select-String 尋找檔案內容的關鍵字


  1. 說明
    1. 查詢檔案內容中的關鍵字
    2. 確認查詢結果的數量
    3. Filter
    4. First
    5. Tail
  2. 應用情境
    1. 搜尋 IIS Logs 404 StatusCode 並且轉為 CSV Format
    2. 搜尋 Code Files 中特定關鍵字
    3. IIS Logs 中的 IP
  3. 相關連結
  4. 參考資料

筆記如何使用 PowerShell 搜尋檔案中的特定關鍵字,示範的情境為對於 IIS Logs 檔進行搜尋。

logo

說明

查詢檔案內容中的關鍵字

Get-Content .\iis.log | Select-String Debug

兩個以上的關鍵字,可以使用下列方式

Get-Content .\iis.log | Select-String 404, 500

如果有更多複雜的規則,則可以使用 Regex 的方式。

確認查詢結果的數量

(Get-Content .\iis.log | Select-String Debug).length

Filter

可以將多個來源的檔案合併讀取,並藉由 Filter 規則挑選檔案

Get-Content .\*.log -Filter *iis*

First

可以篩選前特定列的資料,縮小讀取得檔案範圍,例如下面的方式只會顯示前 10 行

Get-Content .\iis.log -First 10

Tail

也可以從反向從結尾選擇檔案範圍,例如下列方式可以取得最後一筆資料

Get-Content .\iis.log -Tail 1

應用情境

搜尋 IIS Logs 404 StatusCode 並且轉為 CSV Format

Get-Content .\iis.log | Select-String 404 | ConvertTo-Csv

搜尋 Code Files 中特定關鍵字

Get-Childitem -Recurse *.cs | % { $_.FullName; Get-Content $_.FullName | Select-String "keywords"}

IIS Logs 中的 IP

Select-String -Pattern "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" .\logfile.log -AllMatches | % {$_.Matches.Values}

相關連結

PowerShell 使用者不能錯過的 5 個技巧

Powershell 使用物件與資料結構 (Array, Hash)

PowerShell 常用指令筆記

參考資料

MSDocs | Get-Content

MSDocs | Select-String