다른 형식의 파일 수 (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
}
}
}
제안 해 주셔서 감사합니다. 이전에 있었던 것 대신에 if()에 수정 내용을 넣었습니다. 그러나, 나는 지금 [string] $ folderName = $ matches [0]으로 라인에 관련된 오류를 얻는 것처럼 보입니다. 이것은 $ match에 먼저 값을 할당하지 않아서 나 때문일 수 있습니까? 자동으로 값이 할당 된 줄 알았습니까? 감사합니다 – nonfunctionalShell
아니, 아니 하위 폴더. 죄송합니다. 질문을 업데이트합니다. – nonfunctionalShell
@nonfunctionalShell에서 업데이트를 확인하십시오 – Matt