我有以下脚本将单个目录中的大量文件分解为子文件夹,拆分以保持子文件夹大小/文件数可管理。它有效,但有两个我想解决的小问题:
# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0
#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100
$n = 0; Get-ChildItem -File | Group-Object -Property {$script:n++;
[math]::Ceiling($n/9990)} |
ForEach-Object {
$dir = New-Item -Type Directory -Name $_.Name # Create directory
$_.Group | Move-Item -Destination $dir # Move files there
# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"
# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete
$percent -verbose
$i++
}
首先,如何防止脚本本身移动到第一个脚本创建的子文件夹?
其次,如何将名称“Move Files”添加到脚本创建的文件夹中?现在他们只是顺序编号。
通过像这样检查$MyInvocation
来排除脚本本身:
$n = 0; Get-ChildItem -File |Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property { ...
当你调用New-Item
创建目录时,你可以预先添加你想要的-Name
参数:
$dir = New-Item -Type Directory -Name "Move Files $($_.Name)" # Create directory
对于那些需要工作脚本并且不想自己解决更改的人来说,这是工作版本
# MOVE FILES TO FOLDERS
#
# When placed in a parent directory, this Powershell script moves a large number of files (e.g., > 10,000)
# to subdirectories in batches of xxx files. In the case here, in batches of 9,990 files to each
# subdirectory.
# Edit the item in the script ($n/9990) to change the breakpoint for your needs.
# Thanks to Mathias R. Jessen on StackOverflow for helping with the code.
#
# BEGIN SCRIPT
# First count the number of files in the $OrigFolder directory
$numFiles = (Get-ChildItem -Path $OrigFolder).Count
$i=0
#Calculate copy operation progress as a percentage
[int]$percent = $i / $numFiles * 100
$n = 0; Get-ChildItem -File | Where-Object {$_.FullName -ne $MyInvocation.InvocationName} | Group-Object -Property {$script:n++;
[math]::Ceiling($n/9990)} |
ForEach-Object {
$dir = New-Item -Type Directory -Name $_.Name "Move Files $($_.Name)" # Create directory
$_.Group | Move-Item -Destination $dir # Move files there
# Log progress to the screen
Write-Host "$($_.FullName) -> $FolderName"
# Tell the user how much has been moved
Write-Progress -Activity "Copying ... ($percent %)" -status $_ -PercentComplete
$percent -verbose
$i++
}
# END SCRIPT
感谢@ mathias-r-jessen对代码的帮助。