我在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;
}
}
答案 0 :(得分:0)
这里for
循环条件让你太短了:
for($i = 1; $i -le ($filecount/$maxfilecount); $i++) {
例如4 -le 350/100
返回False
,因此您只能获得三个文件夹。您可以将$i
初始化为0
,但这会影响文件夹名称,因此简单地将结束条件增加一个:
for($i = 1; $i -le ($filecount/$maxfilecount + 1); $i++) {