Today I needed to evenly split 40,000 files between 5 directories. The math is simple -- 8,000 files in each directory -- but the way I'd have normally handled a one-off task like this is by using Windows Explorer to go in, manually select the first 8,000 files, drag them into the first target directory, lather, rinse, repeat. However, Explorer decided to be unstable, and I decided to play with PowerShell for a few minutes and see how easy it would be to do it from the shell.
Here's the one-liner I came up with:
for ($($filelist = dir; $i=0); $i -lt 8000; $i++) {Move-Item $filelist[$i] targetdir}
It's a simple for loop that shows off a couple of the nice features of PowerShell:
- I used the filelist variable to hold the return value of the dir cmdlet (which is really just an alias for the Get-ChildItem cmdlet). This cmdlet passes back the child items found in the specified location (or the current directory if none is specified) as a collection, which is stored in the variable.
- I used the for loop to access each individual item in the filelist collection.
Of course, I used the -whatif switch with the Move-Item cmdlet to verify it was going to do what I wanted before actually trying to move the files.