0
1

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.

バッチファイルで、tail -fのようにログを監視する(PowerShellを使用)

0
Last updated at Posted at 2021-09-27

Y子です。

ログファイルなどのテキストファイルを常時監視したい場合、UNIX/Linuxの世界では tail -f という便利なツールがありますが、Windowsでも PowerShell を使えば同じことが簡単に実現できてしまいます。
バッチファイルにしておけば、毎回コマンドを調べる手間もありません。

概要

UNIXのtail -fと同じことを、WindowsのPowerShellを使って実現します。
ショートカットをsendtoフォルダに置けば、右クリックで簡単に実行できます。
確認環境:Windows 10 Home (Bld. 19042.1165)

コード

tail_powershell.bat
powershell Get-Content -Wait -Tail 5 -Path %1
実行結果(例)
> tail_powershell.bat C:\httpd\Apache24\logs\access.log
127.0.0.1 - - [27/Sep/2021:19:02:05 +0900] "GET /htdocs/test/test.php?pref=tokyo HTTP/1.1" 200 1132638
127.0.0.1 - - [27/Sep/2021:19:02:07 +0900] "GET /favicon.ico HTTP/1.1" 404 196
127.0.0.1 - - [27/Sep/2021:19:02:27 +0900] "GET /htdocs/test/test.php?prefj=%E6%9D%B1%E4%BA%AC%E9%83%BD HTTP/1.1" 200 30451
127.0.0.1 - - [27/Sep/2021:19:24:49 +0900] "GET /htdocs/photos/album.php HTTP/1.1" 401 381
127.0.0.1 - - [27/Sep/2021:19:24:49 +0900] "GET /htdocs/photos/album.php HTTP/1.1" 200 707
127.0.0.1 - - [27/Sep/2021:19:24:49 +0900] "GET /favicon.ico HTTP/1.1" 404 196

(※上記例のログはてきとうです…)
バッチファイルの第1引数(%1)を-Pathに渡すことで、ログファイルを開いています。
-Tailに渡している数字は、最初に開いたときに表示する行数です。この数字に関係なく、最新のログがリアルタイムに追加表示されていきます。

使い方

いろいろな使い方があると思いますが、下記に例を紹介します。

  • 上記のバッチファイルに、マウスでログファイルをドロップする
  • SendToフォルダ(「ファイル名を指定して実行」にshell:sendtoで開く)に、上記バッチファイルのショートカットを置き、右クリックメニューの「送る」からログファイルを開く
  • 拡張子「log」のファイルを、上記バッチファイルに関連付け、ダブルクリックで開く

おわりに

ログを出力するソフトを作ったり、運用時にログを監視する際に、便利な技です。
tailしてくれるフリーソフトもありますが、この方法で全く支障ない気がします。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?