2013年11月3日日曜日

ファイル名を置換する

関数


# ------------------------------------------------------------------
# ファイル名を置換する
# 関数名:Replace-FileName
# 引数 :FilePath ファイル名を置換するファイルパス
# :Befor 置換前
# :After 置換後
# 戻り値:なし
# ------------------------------------------------------------------
function Replace-FileName([String]$FilePath, [String]$Befor, [String]$After){
if(Test-Path -LiteralPath $FilePath -PathType Leaf){
$fileInfo = Get-ChildItem -LiteralPath $FilePath
# 置換対象が存在する場合
if($fileInfo.BaseName -match $Befor){
# 置換
$newFileName = ($fileInfo.BaseName -replace $Befor,$After) + $fileInfo.Extension
$newFilePath = Join-Path -Path (Split-Path $FilePath -Parent) -ChildPath $NewFileName
Move-Item -LiteralPath $FilePath -Destination $newFilePath
}
}else{
Write-Host "ファイルが存在しません。ファイル名[ $FilePath ]"
}
}

実行例

$FolderPath = "C:\sample"
$Include = "*.xls"
$Befor = "\["
$After = "【"
Get-ChildItem $FolderPath -Recurse -Include $Include |
ForEach-Object{
  Replace-FileName -FilePath $_.FullName -Befor $Befor -After $After
}

0 件のコメント:

コメントを投稿

注: コメントを投稿できるのは、このブログのメンバーだけです。