我有一个包含许多大文件的文件夹。我想将这些文件分成 3 个文件夹。要求是获取主文件夹中的文件数量,然后将这些文件平均分割到 3 个子文件夹中。示例 - 主文件夹有 100 个文件。当我运行 powershell 时,应创建 3 个子文件夹,分别包含 33、33 和 34 个文件。我们如何使用 Powershell 来做到这一点?
我尝试过以下方法:
$FileCount = (Get-ChildItem C:\MainFolder).count
Get-ChildItem C:\MainFolder -r | Foreach -Begin {$i = $j = 0} -Process {
if ($i++ % $FileCount -eq 0) {
$dest = "C:\Child$j"
md $dest
$j++
}
Move-Item $_ $dest
}
Run Code Online (Sandbox Code Playgroud)
这是另一个解决方案。这说明子文件夹不存在。
# Number of groups to support
$groupCount = 3
$path = "D:\temp\testing"
$files = Get-ChildItem $path -File
For($fileIndex = 0; $fileIndex -lt $files.Count; $fileIndex++){
$targetIndex = $fileIndex % $groupCount
$targetPath = Join-Path $path $targetIndex
If(!(Test-Path $targetPath -PathType Container)){[void](new-item -Path $path -name $targetIndex -Type Directory)}
$files[$fileIndex] | Move-Item -Destination $targetPath -Force
}
Run Code Online (Sandbox Code Playgroud)
如果您需要将文件分成不同数量的组,请使用 $groupCount大于 3 的值。例如,如果计数大于 500,也可以使用 a 来处理逻辑switch,该逻辑将更改为其他内容。$groupCount
逐个循环浏览文件。在我的例子中,作为$fileIndex跟踪器,我们确定文件将被放入的文件夹 0,1 或 2。然后使用该值检查以确保目标文件夹存在。是的,这个逻辑可以很容易地放置在循环之外,但是如果您在脚本运行时更改了文件和文件夹,您可能会认为它更具弹性。
确保该文件夹存在,如果不存在则创建它。然后移动该一项。使用模运算符,就像其他答案一样,我们不必担心有多少文件。让 PowerShell 来计算。
| 归档时间: |
|
| 查看次数: |
5376 次 |
| 最近记录: |