LoginSignup
0
2

More than 3 years have passed since last update.

PowerShell 上で GNU find ライクな検索コマンド

Last updated at Posted at 2019-06-28

はじめに

GNU の findutils に慣れている人が Powershell で実行したいコマンドの一つが find です。
PowerShell では、ファイルを検索するために Get-ChildItem を提供していますが、いちいち API を覚えてもいられない (せっかく苦労して find も覚えたのに・・・) ので、PowerShell 上で GNU find のように Get-ChildItem を呼び出せるラッパー関数を書きました。

コード

以下の関数を $profile に定義してください。

function find {
  param(
    [parameter(Mandatory=$True)]
    [String]$path,
    [String]$name,
    [String]$iname,
    [String]$type,
    [Int]$maxdepth=-1
  )

  $command = "Get-ChildItem -Path $path -Recurse"

  if ($type -eq "f") {
    $command += " -File"
  }
  elseif ($type -eq "d") {
    $command += " -Directory"
  }

  if ($name) {
    $command += " -Filter `"$name`""
  }
  elseif ($iname) {
    $command += " -Filter `"$iname`""
  }

  if ($maxdepth > 0) {
    $command += " -Depth $maxdepth"
  }

  Write-Host $command -ForegroundColor Green
  Invoke-Expression $command
}

Example

上記の find は次のように呼び出すことができます。

find . -type f -name "*.py" -maxdepth 3

まだ必要最低限のパラメータ指定しか出来ないので、今後改良していきたいです。

Reference

0
2
3

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
2