簡単なps1ファイルを書く ファイル名変更

おはようございます。すぎやまです。

この記事では、ps1ファイルを使用してファイル名を変更する方法を紹介します。

まず、結論を記載します。

ps1ファイルでファイル名変更

  • ファイル名の変更は「Rename-Item」コマンドを使用
  • ファイル情報を取得→ファイル名を抜き出し→ファイル名を変更

代表例のコードは下記です。
使用方法はこちらの記事をご覧ください。

# Prompt user for file extension
$fileExtension = Read-Host "対象ファイルの拡張子を入力後、エンターキーを入力してください(例: xlsx,docx,txt,csv ...)"

# Prompt user for the string to be removed from filenames
$oldString = Read-Host "ファイル名の中で、削除したい文字を入力後、エンターキーを入力してください:"

$newString = Read-Host "新たに追加したい文字を入力後、エンターキーを入力してください:"

# Set the target directory to the current directory
$targetDirectory = Get-Location

# Get all files with the specified extension in the target directory
Get-ChildItem -Path $targetDirectory -Filter *.$fileExtension | ForEach-Object {
    $filename = $_.BaseName
    $newFilename = $filename -replace [regex]::Escape($oldString), $newString

    # If the filename has changed, rename the file
    if ($filename -ne $newFilename) {
        $newFilePath = Join-Path -Path $targetDirectory -ChildPath "$newFilename.$fileExtension"
        Rename-Item -Path $_.FullName -NewName $newFilePath
    }
}

Write-Host "Renaming complete."
Pause

下記、詳細を説明します。

使用するコマンド

前述の通り、Rename-Item」コマンドを使用します。

文法機能
Rename-Item[パス] [ファイル名][パス]で指定したファイルを[ファイル名]に変更する

詳細はこちらのサイトをご覧ください。

特定のファイルのみリネーム

# Prompt user for file extension
$fileExtension = Read-Host "対象ファイルの拡張子を入力後、エンターキーを入力してください(例: xlsx,docx,txt,csv ...)"

# Prompt user for the string to be removed from filenames
$oldString = Read-Host "ファイル名の中で、削除したい文字を入力後、エンターキーを入力してください:"

$newString = Read-Host "新たに追加したい文字を入力後、エンターキーを入力してください:"

# Set the target directory to the current directory
$targetDirectory = Get-Location

# Get all files with the specified extension in the target directory
Get-ChildItem -Path $targetDirectory -Filter *.$fileExtension | ForEach-Object {
    $filename = $_.BaseName
    $newFilename = $filename -replace [regex]::Escape($oldString), $newString

    # If the filename has changed, rename the file
    if ($filename -ne $newFilename) {
        $newFilePath = Join-Path -Path $targetDirectory -ChildPath "$newFilename.$fileExtension"
        Rename-Item -Path $_.FullName -NewName $newFilePath
    }
}

Write-Host "Renaming complete."
Pause

こちらのコードでは、
拡張子を指定→追加したい文字を入力→その拡張子のファイルを取得→リネーム
という処理をしています。

使用方法はこちらの記事をご覧ください。

その他のps1ファイル

今回はリネームに焦点を当てましたが、
ps1ファイルを使用するとその他にも様々な処理も行うことができます。

ps1ファイルに可能なことを大まかに知りたい方はこちらの記事を、
実際に使用できるコードを知りたい方はこちらの記事を参照ください。

以上、最後まで読んでくださりありがとうございました。

タイトルとURLをコピーしました