2012-06-10 56 views
2

我正在嘗試重命名文件名中帶有括號的文件。這似乎並不奏效,因爲powershell將[]視爲特殊字符,並不知道該如何操作。使用電源shell重命名文件名中帶有括號的文件

我的電腦上有一個文件夾c:\ test。我希望能夠查看該文件夾並重命名文件的所有文件或部分。下面的代碼似乎工作,但如果文件中有任何特殊字符的代碼失敗:

Function RenameFiles($FilesToRename,$OldName,$NewName){ 

    $FileListArray = @() 
    Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse | Where-Object {$_.attributes -notlike "Directory"}) 
    { 
     $FileListArray += ,@($file) 
    } 

    Foreach($File in $FileListArray) 
    { 
     IF ($File -match $OldName) 
     { 
      $File | rename-item -newName {$_ -replace "$OldName", "$NewName" } 
     } 
    } 
} 

renamefiles -FilesToRename "c:\test" -OldName "testt2bt" -NewName "test" 

我沒有找到一個類似的問題:Replace square bracket using Powershell,但我不知道如何使用的答案的原因,它只是一個解釋錯誤的鏈接:

+0

要刪除,你應該嘗試的支架? – zdan

回答

2

感謝您的幫助你們大家幫很多這是我讀完你的回覆後提出的解決方案。

我有名爲c在我的電腦文件夾:\測試,它有一個文件叫「[ABC] testfile的[XAS] .TXT」,我希望它被稱爲testfile2.txt

Function RenameFiles($FilesToRename,$OldName,$NewName){ 

$FileListArray = @() 
Foreach($file in Get-ChildItem $FilesToRename -Force -Recurse | Where-Object {$_.attributes -notlike "Directory"}) 
{ 
    $FileListArray += ,@($file.name,$file.fullname) 
} 

Foreach($File in $FileListArray) 
{ 
    IF ($File -match $OldName) 
    { 
     $FileName = $File[0] 
     $FilePath = $File[1] 

     $SName = $File[0] -replace "[^\w\[email protected]]", " " 

     $SName = $SName -creplace '(?m)(?:[ \t]*(\.)|^[ \t]+)[ \t]*', '$1' 

     $NewDestination = $FilePath.Substring(0,$FilePath.Length -$FileName.Length) 
     $NewNameDestination = "$NewDestination$SName" 
     $NewNameDestination | Write-Host 

     Move-Item -LiteralPath $file[1] -Destination $NewNameDestination 
     $NewNameDestination | rename-item -newName {$_ -replace "$OldName", "$NewName" } 

     } 
    } 
} 


renamefiles -FilesToRename "c:\test" -OldName "testfile" -NewName "testfile2" 
7
Move-Item -literalpath "D:\[Copy].log" -destination "D:\WithoutBracket.txt" 

使用literalpath開關與布展項目cmdlet的[代替使用重命名項cmdlet的]

+0

這將工作,但我將如何動態創建一個新的名稱與括號,如果你看看我的例子,它會替換所有包含testt2bt在名稱中只有測試的文件。所以我不知道如何動態更改名稱並刪除括號 – justinf

+0

對不起,我沒有得到?即使通過_Move-Item_ [如上所示],您將實現動態重命名。你有沒有在你的樣品中嘗試過? –

8

對於多個文件,這可以用一行完成。爲什麼你不能使用你參考答案上市布展項目建議

get-childitem | ForEach-Object { Move-Item -LiteralPath $_.name $_.name.Replace("[","")} 
+0

這對我很好。我們的工作場所限制了PowerShell腳本。我能夠修改這一行,以刪除每個文件名的前幾個字符。把它放在單行中可以很容易地讓人們粘貼到PowerShell窗口中。感謝帖子! –

相關問題