1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[PowerShell]ファイル内文字列検索、一致数出力スクリプト

Posted at

こんにちは!れーあです。
今回のPowerShellスクリプトはファイル内特定文字列の検索と一致数をファイルに出力するというものです。

前回同様、課題はChatGPTに出してもらいました。

それではどうぞ。

前提情報

スクリプト実行環境

PS C:\Users\user> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      19041  4046

スクリプト内容

今回のスクリプトは下記です。

処理内容:
 検索対象文字列を入力して、その文字列が指定フォルダに
 いくつ存在するか確認する。
 検索結果はファイル名ごとに行を分けてレポートとしてテキスト化する。

WordSearch_in_Log.ps1
# ログファイル格納フォルダ
$LogDir = "C:\Users\user\Desktop"

# 特定キーワード入力
$keyword = Read-Host "Please Search word"

# 検索結果用変数初期化
$TotalFilesProcessed = 0
$MaxMchCnt = 0
$FileWithMostMatchs = ""

# フォルダ内すべての.logファイル検索
$logFiles = Get-ChildItem -Path $LogDir -Filter "*.log"

foreach ($file in $logFiles) {
	# ファイル全行読み込み
	$lines = Get-Content $file.FullName

	# キーワードが含まれる行カウント
	$MchCnt = ($lines | Where-Object { $_ -match $keyword }).Count

	# レポート情報表示
	Write-Output "File: $($file.Name), Total Lines:$($lines.Count), Match Lines: $MchCnt"
	Add-Content -Path $LogDir\Summary_report.txt -Value "File: $($file.Name), Total Lines:$($lines.Count), Match Lines: $MchCnt"


	# サマリーレポート用の情報更新
	$TotalFilesProcessed++
	if ($MchCnt -gt $MaxMchCnt) {
		$MaxMchCnt = $MchCnt
		$FileWithMostMatchs = $file.Name
	}
}

# サマリレポート表示
Write-Output "Total Files Processed: $TotalFilesProcessed"
if ($FileWithMostMatchs -ne "") {
	Write-Output "File with most Matchs: $FileWithMostMatchs ($MaxMchCnt Matchs)"
	Add-Content -Path $LogDir\Summary_report.txt -Value "File with most Matchs: $FileWithMostMatchs ($MaxMchCnt Matchs)"
} else {
	Write-Output "No Matchs found"
	Add-Content -Path $LogDir\Summary_report.txt -Value "No Matchs found"
}

気になる箇所

基本的には使用しているコマンドレットはWirte-OutputやIf文などこれまで使用したもので構成されていますが、新出として「foreach文」が登場しています。

「$file」は「$logFiles」を配列として、その数だけ処理を繰り返します。
今回「$logFiles」にはデスクトップ上に存在する.logファイル名がすべて入っています。つまり、「$file」には配列上1つずつ.logファイル名入ることになります。

実際に動かしてみた

まず実行する前に、デスクトップ上に検証用として、
「test1.log」、「test2.log」、「test3.log」を作成します。
ファイルの内容は下記の通りです。
image.png

上記3ファイル中の「Error」という文字列を検索してみようと思います。
では、デスクトップ上から実際に実行してみます。
image.png

実行すると、検索文字列を聞かれますので、今回は「Error」と入力してエンターキーを押下します。
image.png

実行した結果、デスクトップ上に「Summary_report.txt」が作成され、検索結果がファイル内容として記載されました。
「Error」という文字列が一番多かったのは、「test2.log」だったようです。
image.png

おわりに

ということで今回はファイルの文字列検索および一致した数をファイルに出力するスクリプトを作成しました。
「ファイル出力する」という動作をしていますが、編集すれば、特定の文字列を持つファイルに特定の同じ処理を実行するという風にできるため、処理としては簡単でも内容的にはいい勉強になりました。

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?