用于根据文件数将文件划分为子文件夹的脚本



我在powershell中有一个脚本,可以执行所有文件的计数,并在创建一个子文件夹后不久每100个文件停止一次,但是当我有例如:350个文件,3个文件夹是用100个文件创建的,其他50个被遗漏了,有人可以帮助我,脚本如下:

$path = "c:FILES";
$filecount = (Get-ChildItem $path).Count
$maxfilecount = 100;
#endregion variables
#region functions
# Define Write-DateTime function to alias
function Write-DateTime {
    return (Get-Date).ToString("yyyyMMdd hh:mm:ss");
}
# Set alias for quick reference
Set-Alias -Name wdt -Value "Write-DateTime";
#endregion functions
#region Script Body
# Output status to host.
Write-Output "$(wdt): Gathering file names.";
# Get file count
$filecount = (Get-ChildItem $path | Where-Object {$_.PSIsContainer -ne $true}).Count;
# Output status to host.
Write-Output "$(wdt): Processing files.";
# Enumerate folders based on filecount and maxfilecount parameter
for($i = 1; $i -le ($filecount/$maxfilecount); $i++) {
    # Clear the $files objects.
    $files = $null;
    # Set the foldername to zero-filled by joining the $path and counter ($i)
    $foldername = Join-Path -Path ($path) -ChildPath ("Disc-{0:0}" -f $i);
    # Output status to host.
    Write-Output "$(wdt): Creating folder $foldername.";
    # Create new folder based on loop counter
    New-Item -Path $foldername -ItemType Directory | Out-Null;
    # Output status to host. 
    Write-Output "$(wdt): Gathering files for $foldername.";
    # Break files into smaller collections to move to subfolders.
    $files = Get-ChildItem $path | Where-Object {$_.PSIsContainer -ne $true} | select -first $maxfilecount;
    # Output status to host.
    Write-Output "$(wdt): Moving files to $foldername.";
    # Enumerate collection.
    foreach($file in $files) {
        # Output status to host.
        Write-Output "$(wdt): Moving $($file.fullname).";
        # Move files in collection to subfolder.
        Move-Item -Path $file.fullname -Destination $foldername;
    }
}

这里的for循环条件让你太短了:

for($i = 1; $i -le ($filecount/$maxfilecount); $i++) {

例如,4 -le 350/100返回False,因此您只会得到三个文件夹。您可以将$i初始化为 0 ,但这会影响文件夹名称,因此只需将结束条件增加 1:

for($i = 1; $i -le ($filecount/$maxfilecount + 1); $i++) {