1

我有大量文件要根据文件名的第一部分归档在文件夹中。文件名 -> 文件夹名称由特定字符分隔:[-] [,] [and]。例子:

第一个文件名 - 2016-04.pdf 第二个文件名和另一个名称.mp3 第三个.jpg 第四个文件名,2016.pdf

我希望生成的文件夹名称不包括 [\s-] [,\s] [\sand\s] 部分。

这是我的脚本,它可以工作,除了文件夹名称包含我不想要的东西,例如:

第一个文件夹名称 - 第四个文件名,

认为这与我的正则表达式匹配贪婪地包含连字符(特别是)有关,但我不确定如何格式化查询和创建后续文件夹名称。

此外,用“####”注释掉的东西(如进度指示器)不起作用。如果您有任何建议,请发表评论。无论如何,我都不是程序员。

$OrigFolder = ".\"
$NewFolder = ".\_Sorted to Move"

# Orphans folder, where files that return null in the regex match will be moved
# Example: file "- title.mp4"
# will be moved to ".\Sorted\_Orphans" folder

$Orphans = '_Orphans' # Use the underscore to sort the folder to the top of the window

#### How to use an array of values for the delimiters in the regex instead of literals
#### My proposed code, but I am missing how o use the delims in the regex match
#### $delims = "\s-\s" ",\s"\s and\s"

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

# Tell the user what will happen
clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $OrigFolder ' to _Sorted to Move'

# Ask user to confirm the copy operation
Read-host -prompt 'Press enter to start copying the files'

# Regex to match filenames
$Regex = [regex]"(^\s*(.*?)\s*-)|(^\s*(.*?),)|(^\s*(.*?)\s*and\s)"

    # Loop through the $OrigFolder directory, skipping folders
Get-ChildItem -LiteralPath $OrigFolder | Where-Object {!$_.PsIsContainer} |
    ForEach-Object {
        if($_.BaseName -match $Regex){

            #### Caluclate copy operation progress as a percentage
            #### [int]$percent = $i / $numFiles * 100

            # If first part of the file name is empty, move it to the '_Orphans' folder
            if(!$Matches[1]){
                $ChildPath = $Orphans
            } else {
                $ChildPath =  $Matches[1]
            }

# Generate new folder name
$FolderName = Join-Path -Path $NewFolder -ChildPath $ChildPath

# Create folder if it doesn't exist
    if(!(Test-Path -LiteralPath $FolderName -PathType Container)){
        $null = New-Item -Path $FolderName -ItemType Directory
    }

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Move the file to the folder
            Move-Item -LiteralPath $_.FullName -Destination $FolderName

##### Tell the user how much has been moved
##### Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
##### $i++

    }
}

Write-Host 'Total number of files in '$OrigFolder ' is ' $numFiles
Write-Host 'Total number of files copied to '$NewFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

非常感谢 StackOverflow 用户的帮助以及我在上面拼凑的代码片段。

4

2 回答 2

1

以下正则表达式应该找到您不需要的任何分隔符(使用非捕获组):

(?:\s-)|(?:,\s)|(?:\sand\s)

这是演示

现在您所要做的就是使用-replace该正则表达式来摆脱它们:

if($_.BaseName -match $Regex)
{
    $ChildPath = $_.BaseName -replace $Regex

    # copy...
}

另外,请查看Write-Progress 帮助

如果没有出现进度条,请检查 $ProgressPreference 变量的值。如果该值设置为 SilentlyContinue,则不显示进度条。有关 Windows PowerShell 首选项的详细信息,请参阅 about_Preference_Variables。cmdlet 的参数对应于 ProgressRecord 类 (System.Management.Automation.ProgressRecord) 的属性。有关详细信息,请参阅 Windows PowerShell 软件开发工具包 (SDK) 中的 ProgressRecord 主题。

于 2016-05-01T17:29:45.367 回答
0

这是将我的 .pdf 文件(杂志)移动到以杂志标题命名的子目录的完整脚本。感谢 jisaak (Martin Brandl) 帮助我解决了正则表达式问题。将“杂志”添加到新文件夹的解决方案位于第 46/47 行。对大多数人来说可能很明显,但我花了一个小时才弄清楚。

我会喜欢关于简化代码和修复缩进等的建议。我对 Powershell 的风格尚不了解,这是我的第一次尝试

$OrigFolder = "T:\Magazines"
$NewFolder = "T:\Magazines\_Sorted to Move"

# Orphans folder, where files that return null in the regex match will be moved
# Example: file "- title.pdf"
# will be moved to ".\Sorted\_Orphans" folder

$Orphans = '_Orphans' # Use the underscore to sort the folder to the top of the window

#### How to use an array of values for the delimiters in the regex instead of literals
#### My proposed code, but I am missing how o use the delims in the regex match
#### $delims = "\s-\s" ",\s"\s and\s"

# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0

# Tell the user what will happen
clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $OrigFolder ' to _Sorted to Move'

# Ask user to confirm the copy operation
Read-host -prompt 'Press enter to start copying the files'

# Regex to match filenames
$Regex = [regex]"(?:(.*?)\s-)|(?:(.*?),\s)|(?:(.*?)\sand\s)"

# Loop through the $OrigFolder directory, skipping folders
Get-ChildItem -LiteralPath $OrigFolder | Where-Object {!$_.PsIsContainer} |
    ForEach-Object {
        if($_.BaseName -match $Regex){
        $ChildPath = $_.BaseName -replace $Regex

#Caluclate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100


# If first part of the file name is empty, move it to the '_Orphans' folder
if(!$Matches[1]){
    $ChildPath = $Orphans}
else {
    $ChildPath = $Matches[1]
    }


# Generate new folder name and append ' Magazine' to the new folder name
$FolderName = Join-Path -Path $NewFolder -ChildPath ($ChildPath + ' Magazine')

# Create folder if it doesn't exist
    if(!(Test-Path -LiteralPath $FolderName -PathType Container)){
    $null = New-Item -Path $FolderName -ItemType Directory}

# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"

# Move the file to the folder
Move-Item -LiteralPath $_.FullName -Destination $FolderName

# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
$i++
    }
}

Write-Host 'Total number of files in '$OrigFolder ' is ' $numFiles
Write-Host 'Total number of files copied to '$NewFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

我也为我的多媒体文件和图片修改了脚本,你不知道这会节省我多少时间。再次感谢你,马丁!

于 2016-05-01T22:44:58.077 回答