銀河鉄道

【PowerShell】今いるフォルダのファイル名を一覧表示する(最下層まで含む)

サムネイル
[PowerShell]Display allin the terminal
何があるか
一覧表示

わざわざポチポチせずに一覧を見たい

ターミナル上で一覧表示をしよう

スクリプト

param(
    [string]$Path = ""
)

# --- 開始パスの設定 ---
if ([string]::IsNullOrWhiteSpace($Path)) {
    $StartingPath = (Get-Location).Path
    Write-Host "Starting path not specified. Using current directory: $StartingPath" -ForegroundColor DarkGray
} else {
    $StartingPath = Resolve-Path -Path $Path
    Write-Host "Starting path specified: $StartingPath" -ForegroundColor DarkGray
}

# --- ファイルとフォルダーを取得 ---
$items = Get-ChildItem -Path $StartingPath -Recurse -Force |
          Select-Object FullName, Name, LastWriteTime

# --- ディレクトリ単位でグループ化 ---
$List = foreach ($item in $items) {
    $ParentPath = Split-Path -Path $item.FullName -Parent
    [PSCustomObject]@{
        Directory    = $ParentPath
        File         = $item.Name
        LastWriteTime = $item.LastWriteTime
    }
}

$List |
    Group-Object Directory |
    Sort-Object Name |
    ForEach-Object {
        $dir = $_.Name
        if ([string]::IsNullOrWhiteSpace($dir)) { $dir = '.' }
        Write-Host "Directory: $dir" -ForegroundColor Cyan

        $files = $_.Group | Where-Object { $_.File }
        if ($files.Count -eq 0) {
            Write-Host "(no files)" -ForegroundColor DarkGray
        } else {
            foreach ($f in $files | Sort-Object File) {
                $time = $f.LastWriteTime.ToString("yyyy/MM/dd HH:mm")
                Write-Host "$($f.File)  ($time)"
            }
        }
        Write-Host ""
    }

# --- 削除確認処理 ---
Write-Host "空行で区切ります"
Write-Host ""
Write-Host "注意: PowerShellスクリプトファイル(.ps1)は除外されます。" -ForegroundColor Yellow

$filesToDelete = $items | Where-Object { $_.Extension -ne ".ps1" }

Write-Host "対象外を除いた削除候補ファイル数: $($filesToDelete.Count)" -ForegroundColor DarkYellow
$confirmation = Read-Host "削除を実行しますか? (Yes/No)"

if ($confirmation -eq "yes") {
    Write-Host "削除を実行しています..." -ForegroundColor Green
    $filesToDelete | Remove-Item -Force
    Write-Host "削除が完了しました。" -ForegroundColor Green
} else {
    Write-Host "削除をスキップしました。" -ForegroundColor DarkYellow
}

何をやってるか?

  1. 起点ディレクトリを設定
    • 引数 $Path がなければ、カレントディレクトリを使う。
  2. 全ファイル・フォルダを再帰的に取得
    • Get-ChildItem-Recurse -Force で実行。
  3. 親ディレクトリごとにグループ化して表示
    • 各フォルダごとにファイル名+更新日時を整形出力。
  4. 削除対象確認(.ps1除外)+ユーザー確認
    • .ps1 ファイル以外を削除候補にして、
      Read-Host で “Yes” 入力したときだけ削除実行。

改善ポイント

  1. -ErrorAction SilentlyContinue を追加
     → 権限エラーで止まらないようにする
  2. ログ出力機能を追加(例:削除ログ.txt)
     → いつ何を削除したか記録できると安心
  3. 関数化して再利用可能にする
  4. 「特定フォルダ以下の1日以上前のファイルだけ削除」とかに拡張する

Vocabulary

Clean up | クリーンアップ
Directory | ディレクトリ
Recurse | 再帰的
Group-Object | グループ化
Remove-Item | ファイル削除
Confirmation | 確認プロンプト
ForegroundColor | 文字色設定

Clean your workspace,
not your history.

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧