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

PowerShell 基礎操作— ファイルと内容検索を極める

0
Posted at

はじめに

PowerShell を使い始めて、最初につまずきやすいのが次の操作です。

  • ファイルを探したい
  • 特定の文字列を含むファイルを見つけたい
  • アクセス拒否エラーで処理が止まる

本記事では、PowerShell におけるファイル探索と内容検索を、
「考え方 → 正しい書き方 → よくある落とし穴」の順で解説します。


PowerShell における「ファイル検索」の基本思想

PowerShell では、検索は2段階で考えます。

  1. ファイルを列挙する
  2. 条件で絞り込む / 内容を調べる

👉 この分離がとても重要です。


ファイルを探す:Get-ChildItem

PowerShell でファイルやディレクトリを列挙する基本コマンドは:

Get-ChildItem

これは CMD の dir に相当します。

指定したディレクトリの中を見る

Get-ChildItem C:\Users

再帰的にすべて見る

Get-ChildItem C:\Users -Recurse

ファイル名で絞り込む

拡張子で探す

Get-ChildItem C:\Users -Recurse -Filter "*.txt"

📌 ポイント

  • -Filter高速
  • ファイルシステム側で絞り込まれる

名前に特定文字列を含むファイル

Get-ChildItem C:\Users -Recurse |
Where-Object Name -like "*config*"

「アクセス拒否」で止まらないために

全体検索をすると、必ず次のエラーに遭遇します。

Access to the path is denied

これは 正常な挙動 です。

正しい対処法

Get-ChildItem C:\Users -Recurse -ErrorAction SilentlyContinue

👉 エラーを無視して 処理を継続 します。


ファイル内容を読む:Get-Content

ファイルの中身を表示

Get-Content example.txt

ファイル全体を一気に読む

Get-Content example.txt -Raw

-Raw文字列として一括読み込み するため、
後続処理に向いています。


内容検索の本命:Select-String

PowerShell における grep に相当するのが:

Select-String

特定文字列を含むファイルを探す

Get-ChildItem C:\Users -Recurse -ErrorAction SilentlyContinue |
Select-String "password"

処理の流れは:

  1. ファイルを列挙
  2. 内容を検索

なぜ Select-String -Recurse が使えないことがあるのか

古い PowerShell 環境では、次の書き方は エラー になります。

Select-String -Path C:\Users\* -Recurse

理由:

  • Select-String-Recurse が存在しないバージョンがある

互換性の高い正解パターン

Get-ChildItem C:\Users -Recurse |
Select-String "API_KEY"

この書き方が最も安全です。


検索結果から「ファイル名だけ」を得る

Get-ChildItem C:\Users -Recurse |
Select-String "API_KEY" |
Select-Object -ExpandProperty Path -Unique

C:\Users\Administrator> Get-ChildItem C:\Users -Recurse |
Select-String "API_KEY" |
Select-Object -ExpandProperty Path -Unique
C:\Users\Public\Music\config.xml

CTF / 調査 / 監査で非常によく使われます。


よくある誤解

PowerShell は遅い

→ 使い方が悪いだけ

  • いきなり C:\ 全体を再帰
  • 無制限に Select-String

検索範囲を絞るのが基本


実務・セキュリティ視点での検索例

設定ファイルに含まれる秘密情報

Get-ChildItem C:\Users -Recurse -Include *.txt,*.env,*.config |
Select-String "KEY|TOKEN|SECRET"

最近作成されたファイル

Get-ChildItem C:\Users -Recurse |
Where-Object LastWriteTime -gt (Get-Date).AddDays(-3)

まとめ

  • ファイル検索は Get-ChildItem
  • 内容検索は Select-String
  • 再帰は Get-ChildItem 側で行う
  • エラーは SilentlyContinue で制御
  • PowerShell は「段階的に考える」と強い
0
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
0
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?