# Maximum number of folders to create

**URL:** <https://forums.powershell.org/t/maximum-number-of-folders-to-create/18249>\
**Category:** PowerShell Help\
**Created:** [December 28, 2021, 7:12pm UTC](https://forums.powershell.org/t/maximum-number-of-folders-to-create/18249 "2021-12-28T19:12:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![valerie-knopfel](https://avatars.discourse-cdn.com/v4/letter/v/919ad9/32.png) [@valerie-knopfel](https://forums.powershell.org/u/valerie-knopfel)\
**Post date:** [December 28, 2021, 7:12pm UTC](https://forums.powershell.org/t/maximum-number-of-folders-to-create/18249/1 "2021-12-28T19:12:29Z")

</div>

Trying to figure out how to set a maximum number of sub folders to create in a folder and then moving a specific number of files into each folder, leaving the remaining files in the original location after reaching the max folders and files per folder.  
Below script works fine creating a “Sorted” subfolder and then subfolders beneath the subfolders and moving the files into it but I am having difficulty with adding the maximum number of subfolders to create under the “Sorted” subfolder…

```
 $filesperfolder = 2
 $folderMax = 3
 $files = '*.txt'
 $sourcePath = "Path to source files"
 $destPath = "Destination Path"
 $i = 0;
 $folderNum = 1;

 Get-ChildItem "$sourcePath\$files" | % {

while($folderNum -le $folderMax)
{     
New-Item -Path ($destPath + "\" + $folderNum) -Type Directory -Force
}
Move-Item $_ ($destPath + "\" + $folderNum);
$i++;
if ($i -eq $filesperfolder){
    $folderNum++;
    $i = 0 ;
   }
 }

```

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [December 28, 2021, 8:09pm UTC](https://forums.powershell.org/t/maximum-number-of-folders-to-create/18249/2 "2021-12-28T20:09:10Z")

</div>

You have to put the actions of increasing the `$folderNum` and the `Move-Item` stuff inside the while loop. Otherwise your while loop runs forever because your condition never changes.

Additional tip for the future:  
Something like this becomes obvious when you simply output your variables to the console inside loops or after they’ve been changed in the code.

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:19pm UTC](https://forums.powershell.org/t/maximum-number-of-folders-to-create/18249/3 "2024-05-16T20:19:52Z")

</div>


