Windows PowerShellをさわってみる その3

前々回にJPEGファイルに連番を付けてファイルをコピーするスクリプトを作ったが、今回はそれを改造して対話型にしてみた。

# 定数
Set-Variable Choice_Type Management.Automation.Host.ChoiceDescription -Option Constant

# フォルダの選択ダイアログを表示して、フォルダを選択させる。
function browseFolder([string]$title="フォルダを選択してください") {
    $shell = New-Object -com Shell.Application
    $folder = $shell.BrowseForFolder(0, $title, 1, 0)
    
    if($folder -eq $null) { return $null }
    
    return $folder.Self.Path
}

# フォルダパスの入力を促して、フォルダパスを取得します。
function inputFolder([string]$title) {
    $choice = [Management.Automation.Host.ChoiceDescription[]](
        (New-Object $Choice_Type("直接入力(&I)", "文字列として直接入力する")),
        (New-Object $Choice_Type("ダイアログ(&D)", "ダイアログを表示して、選択する"))
    )
    $answer = $Host.UI.PromptForChoice($null, $title, $choice, 1)

    if($answer -eq 0) {
        $path = Read-Host パス
    } else {
        $path = browseFolder
    }
    return $path
}

# フォーマットの入力を促して、フォーマット文字列を取得します。
function inputFormat {
    $choice = [Management.Automation.Host.ChoiceDescription[]](
        (New-Object $Choice_Type("入力(&I)", "入力する")),
        (New-Object $Choice_Type("規定値(&D)", "連番のみ"))
    )
    $answer = $Host.UI.PromptForChoice($null,
        "ファイル名のフォーマットを指定してください(連番は自動で付加されます)", $choice, 0)
    
    if($answer -eq 0) {
        $format = Read-Host フォーマット
    } else {
        $format = ""
    }
    return $format + "{0:#000}"
}

$format = inputFormat
$srcPath = inputFolder("コピー元のフォルダを選択してください")
$dstPath = inputFolder("コピー先のフォルダを選択してください")

# コピー先フォルダからファイルを全削除
Get-ChildItem $dstPath *.jpg | Remove-Item

$index = 0
$files = Get-ChildItem $srcPath *.jpg

foreach($file in $files) {
    $fileName = [string]::Format("$format" + ".jpg", $index++)
    $fileName = Join-Path $dstPath $fileName

    Copy-Item $file.FullName $fileName
    Write-Progress "Copy File" $file.Name -PercentComplete (($index / $files.Length) * 100)
}

使い勝手がいいかどうかは別として、いろんな事をやってみた。
Set-Variableで変数を定数にすることができる。
$Host.UI.PromptForChoiceメソッドを使うと選択肢を表示して、そこから項目を選択させることができる。
Write-Progressで進捗状況をプロンプトに表示することができる。
結構いろんな事ができるので、楽しくなってきた。