2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellでファイル名を複雑なパターンで置換する方法

Last updated at Posted at 2013-02-20

ファイル名を切ったり貼ったりして加工してファイル名を置換する場合、コマンドプロンプトでは難しかったのでPowerShellで実装しました。
忘れかけてたので個人的なメモがてら。

ReplaceFile.ps1
# カレントディレクトリに移動
cd "対象ディレクトリ";

# 各ファイルに対して操作
Get-ChildItem | ForEach-Object
{
	# ファイル名を'-'で区切ってみたり
	$data = $_.Name.Split('-');
	
	# ファイル名が"H"で始まってたら除外したり
	if($data[0][0] -ne 'H')
	{
		# 新しいファイル名を並び替えで作ったり
		$newname = $data[1] + "-" + $data[0] + "-" + $data[2];
		
		# pdfじゃなかったら末尾に"-abs.pdf"を追加したりして
		if(!($newname.EndsWith(".pdf")))
		{
			$newname += "-abs.pdf";
		}
		
		# ファイル名を変更
		Rename-Item $_ -newName $newname;
	}
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?