2012-06-10 2 views
2

파일 이름에 괄호가있는 파일의 이름을 바꾸려고합니다. powershell이 ​​[] 문자를 특수 문자로보고 무엇을해야할지 모르기 때문에이 방법은 효과가없는 것 같습니다.파워 쉘을 사용하여 파일 이름에 괄호가있는 파일 이름 바꾸기

내 컴퓨터에 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라는 내 PC에있는 폴더가 : \ 테스트를하고 그것이라고에 파일이 있습니다 "[ABC] testfile 위 [XAS]가 .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" 
testfile2.txt 호출 할
7
Move-Item -literalpath "D:\[Copy].log" -destination "D:\WithoutBracket.txt" 

를 사용하여 이동 품목 cmdlet을 [대신 이름 바꾸기 항목 cmdlet을 사용]으로 literalpath 스위치 도움말들에 대한

+0

그럴 것이지만, 예제에서 보면 testt2bt가 포함 된 모든 파일을 테스트로 바꾸는 대신 동적으로 새 이름을 대괄호로 묶는 방법은 어떨까요? 그래서 동적으로 이름을 변경하고 괄호를 제거하는 방법을 모르겠다 – justinf

+0

미안하지만, 못 봤어? _Move-Item_ [위 그림과 같이]을 사용하여 동적 이름 변경을 수행 할 수 있습니다. 샘플에서 해봤습니까? –

8

여러 파일의 경우 한 줄로 수행 할 수 있습니다. 당신이 참조하는 대답에 나와있는 이동 항목의 제안을 사용할 수없는 이유

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

이것은 나를 위해 잘 작동했습니다. 우리 직장에서는 파워 쉘 스크립트를 제한합니다. 이 한 줄을 수정하여 각 파일 이름의 처음 몇 글자를 제거 할 수있었습니다. 한 줄로 만들면 사람들에게 Powershell 창에 붙여 넣기가 쉬워졌습니다. 게시물을 가져 주셔서 감사합니다! –