2014-11-26 3 views
2

다른 형식의 파일 수 (pdf, xls, jpeg 등)로 가득 찬 폴더 (하위 폴더 없음)가 있습니다. 파일에는 공통 이름 지정 구조가 없으며 파일 이름의 어딘가에 PN이라는 문자가오고 그 다음에 6 자리 숫자가 오는 패턴 만 관련되어 있습니다. PNxxxxxx 코드는 파일 이름의 시작, 끝, 공백 또는 다른 문자 사이의 임의의 지점에서 발생할 수 있습니다.powershell의 파일 이름을 기반으로 새 위치로 파일 이동

여러 파일이 동일한 PN 코드를 공유 할 수 있습니다. 예를 들어 pdf, xls 및 jpeg는 모두 제목에 PN854678을 가질 수 있습니다.

필자는 모든 코드를 동일한 코드를 공유 할 수있는 다른 파일과 함께 폴더 (아직 존재하지 않을 수도 있음)에 배치 할 새 위치로 모든 파일을 이동하려고하는 스크립트를 작성했습니다. 폴더에는 이름으로 올바른 6 자리가 오는 PN이 있어야합니다.

스크립트를 실행하려고해도 오류가 발생하지 않습니다. 코드가 실행됩니다. 소스와 대상 폴더는 변경되지 않습니다. 그냥 확인하려면 set-executionpolicy remotesigned을 사용하고 cmd.exe를 사용하여 스크립트를 실행 해 보았습니다.

다음은 코드입니다.이 첫 번째 시도는 powershell을 사용하고 있으며 일반적으로 스크립팅에 익숙하지 않으므로 어리석은 실수를 한 경우 사과드립니다.

# Set source directory to working copy 
$sourceFolder = "C:\Location A" 

#Set target directory where the organized folders will be created 
$targetFolder = "C:\Location B" 

$fileList = Get-Childitem -Path $sourceFolder 
foreach($file in $fileList) 
{ 
    if($file.Name -eq "*PN[500000-999999]*") #Numbers are only in range from 500000 to 999999 
    { 

     #Extract relevant part of $file.Name using regex pattern -match 
     #and store as [string]$folderName 

    $pattern = 'PN\d{6}' 

     if($file.Name -match $pattern) 
     {   
      [string]$folderName = $matches[0]   
     } 


    #Now move file to appropriate folder 

    #Check if a folder already exists with the name currently contained in $folderName 
     if(Test-Path C:\Location B\$folderName) 
     { 
      #Folder already exists, move $file to the folder given by $folderName 
      Move-Item C:\Location A\$file C:\Location B\$folderName     
     } 
      else 
     { 
      #Relevant folder does not yet exist. Create folder and move $file to created folder 
      New-Item C:\Location B\$folderName -type directory 
      Move-Item C:\Location A\$file C:\Location B\$folderName 
     } 

    } 
} 

답변

3

파일이 모두 하나의 폴더 또는 하위 폴더에 있습니까? 당신은 그것을 언급하지는 않지만 하위 폴더에서 결과를 얻으려면 -recurseGet-Childitem에 사용해야한다는 것을 명심하십시오. 문제의 출처는이 절 $file.Name -eq "*PN[500000-999999]*"입니다. -eq은 wlidcards를 처리하기위한 것이 아닙니다. 이 단순 대체품을 제안하겠습니다.

$file.Name -match 'PN\d{6}' 

그러나 숫자를 특정 범위로 지정해야합니다. 조금이라도 업데이트하면됩니다.

# Set source directory to working copy 
$sourceFolder = "C:\Location A" 

#Set target directory where the organized folders will be created 
$targetFolder = "C:\Location B" 

foreach($file in $fileList) 
{ 
    # Find a file with a valid PN Number 
    If($file.Name -match 'PN[5-9]\d{5}'){ 
     # Capture the match for simplicity sake 
     $folderName = $matches[0] 

     #Check if a folder already exists with the name currently contained in $folderName 
     if(!(Test-Path "C:\Location B\$folderName")){New-Item "C:\Location B\$folderName" -type directory} 

     #Folder already exists, move $file to the folder given by $folderName 
     Move-Item "C:\Location A\$file" "C:\Location B\$folderName"     
    } 

} 
  1. 인용 당신의 문자열을 잊지 마십시오. 변수를 큰 따옴표로 묶은 문자열에 넣을 수 있으며 적절하게 확장됩니다.
  2. $file.Name -match 'PN([5-9]\d{5})' PN을 포함하는 파일을 찾은 다음 5에서 9 사이의 임의의 숫자를 입력 한 다음 5 자리수를 더한 파일을 찾습니다. 그러면 500000-999999 기준을 따라야합니다.
  3. 어쨌든 파일을 이동하려고합니다. Move-Item으로 두 줄의 라인을 사용하는 것은 의미가 없습니다. 대신 경로를 확인하십시오. 그렇지 않으면 (!) 거기에 폴더를 만듭니다.
+0

제안 해 주셔서 감사합니다. 이전에 있었던 것 대신에 if()에 수정 내용을 넣었습니다. 그러나, 나는 지금 [string] $ folderName = $ matches [0]으로 라인에 관련된 오류를 얻는 것처럼 보입니다. 이것은 $ match에 먼저 값을 할당하지 않아서 나 때문일 수 있습니까? 자동으로 값이 할당 된 줄 알았습니까? 감사합니다 – nonfunctionalShell

+0

아니, 아니 하위 폴더. 죄송합니다. 질문을 업데이트합니다. – nonfunctionalShell

+0

@nonfunctionalShell에서 업데이트를 확인하십시오 – Matt

관련 문제