Вопрос

I have 10K documents in a directory with this type of naming convention:

1050_14447_Letter Extension.pdf, 1333_14444_Letter.docx, etc...

I tried using this script to remove all characters before the 2nd underscore (including the 2nd underscore):

Get-ChildItem -Filter *.pdf | Rename-Item -NewName {$_.Name -replace '^[0-9_]+'}

This worked, but revealed there would be duplicate file names.

Wondering if there is some way a script can create a subfolder based on the filename (minus the extension)? So there would be 10K subfolders in my main folder. Each subfolder would just have the one file.

Это было полезно?

Решение

This should work. It creates a new folder for each item, then moves it, renaming it in the process.

gci | ? {!$_.PSIsContainer} | % {New-Item ".\$($_.BaseName)" -Type Directory; Move-Item $_ ".\$($_.BaseName)\$($_.Name -replace '^[0-9_]+')"}

Note that if there are two files with the same name, but different extensions, you'll see an error when trying to create the directory, but both files will wind up in the same folder.

Alternately, if you want something more readable to save in a script, this is functionally identical:

$files = Get-ChildItem | Where-Object {!$_.PSIsContainer}
foreach ($file in $files)
{
    $pathName = ".\" + $file.BaseName
    New-Item $pathName -Type Directory
    $newFileName = $pathName + "\" + ($file.Name -replace '^[0-9_]+')
    Move-Item $file $newFileName
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top