3
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.

PowerShellからfind.exeを実行する時に注意点

Posted at

MSLearn - find

find.exeはWindowsのコマンドプロンプトで指定したファイル内テキストをパターン検索してくれるコマンドとなります。

このコマンドをコマンドプロンプトから実行する場合は特に気を付ける必要はないのですが。
PowerShellから実行する場合はちょっと注意が必要なので本記事ではその点について説明する。

find.exeでは<"string">のように文字列をダブルクオートで囲む必要がある

find.exe Syntax

find.exeのSyntaxを読むと、下記赤枠のように<"string">と記載があります。

image.png

これはfind.exeで検索を行う場合に、文字列指定は"String"といったように、ダブルクオートで囲む必要を表しています。

それぞれhello(hello.txt),world(world.txt),helloworld(helloworld.txt)のようにテキスト(ファイル名)したテキストとファイル名が同一のファイルを用意して、helloという文字列で検索をかけてみます。

rem 文字列 hello を *.txtを対象に検索
find.exe "hello" *.txt

image.png

コマンドプロンプトでは上記のように検索できました。

この時点でPowerShellを普段ご利用の方はいやな予感がしてきているかと思いますが。

同様のコマンドをPowerShellから実行すると下記のようにエラーになります。

image.png

この動作が何に起因するかといえば、下記のドキュメントにあるように

about_Quoting_Rules

PowerShellではダブルクオートで囲まれた文字列は展開してしまうしようとなっているため。

find.exeでは文字列として"String"といった形で渡す必要があるるが、PoweShellでは展開されてダブルクオートがなくなってしまう事に起因していそうです。

回避するためには下記のようにシングルクオートでさらに囲んで、文字列が展開されないようにエスケープしてあげればOK

find.exe '"hello"' *.txt

image.png

ちなみにfindstr.exeではダブルクオートは必要ない

MSLearn - findstr.exe

似たコマンドとしてfindstr.exeがありますが、こちらはSyntaxを見てみるとfind.exeと異なり、<strings>といった具合でこちらのコマンドはダブルコーテーションでくくる必要がないため、PowerShellから実行する際は、こちらを利用すれば手間は少ない。

image.png

そもそもSelect-Stringでよくない?

PowerShellのコマンドレットには、Select-Stringというコマンドレットが用意されてる。

このコマンドレットはfindstr.exeと同様にファイルを文字列検索する機能を提供している。

総評

PowerShellを使っているとダブルクオートの部分で失敗する事があるかと思います。

PowerShellからネイティブコマンドを実行するに注意する一つのポイントかと思います。

3
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
3
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?