2013年9月3日火曜日

ファイル名に角括弧[]がついてるとRename-Itemで失敗する

概要

ファイル名に角括弧[]がついてるとRename-Itemで失敗するので、Move-Itemを代用する

関数

# ------------------------------------------------------------------
# ファイル名をリネームする
# 関数名:Rename-File
# 引数  :FilePath 名前を変更するファイルパス
#       :NewFileName 新しいファイル名前
# 戻り値:なし
# ------------------------------------------------------------------
function Rename-File([String]$FilePath, [String]$NewFileName){
  if(Test-Path -LiteralPath $FilePath -PathType Leaf){
    $newFilePath = Join-Path -Path (Split-Path $FilePath -Parent) -ChildPath $NewFileName
    Move-Item -LiteralPath $FilePath -Destination $newFilePath
  }else{
    Write-Host "ファイルが存在しません。ファイル名[ $FilePath ]"
  }
}
 
# ------------------------------------------------------------------
# フォルダ名をリネームする
# 関数名:Rename-Folder
# 引数  :FolderPath 名前を変更するフォルダパス
#       :NewFolderName 新しいフォルダ名前
# 戻り値:なし
# ------------------------------------------------------------------
function Rename-Folder([String]$FolderPath, [String]$NewFolderName){
  if(Test-Path -LiteralPath $FolderPath -PathType Container){
    $newFolderPath = Join-Path -Path (Split-Path $FolderPath -Parent) -ChildPath $NewFolderName
    if(Test-Path -LiteralPath $FolderPath -PathType Container){
      Write-Host "既に存在するフォルダを作成することはできません。フォルダー名[ $FolderPath ]"
    }else{
      Move-Item -LiteralPath $FolderPath -Destination $newFolderPath
    }
  }else{
    Write-Host "フォルダが存在しません。フォルダ名[ $FolderPath ]"
  }
}

実行例

Rename-File -FilePath "C:\[20130903]新規要件定義\[20130903]Webログイン.xls" -NewFileName "Webログイン.xls"
Rename-Folder -FolderPath "C:\[20130903]新規要件定義" -NewFolderName "[20130903]要件定義"

0 件のコメント:

コメントを投稿

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