I need a batch script to randomly select X number of files in a folder and move them to another folder. How do I write a windows batch script that can do this?
The following Batch code will do it. Note that you will need to launch cmd using the following command line:
cmd /v:on
to enable delayed environment variable expansion. Note also that it will pick a random number of files from 0 to 32767 - you will probably want to modify this part to fit your requirements!
@ECHO OFF
SET SrcCount=0
SET SrcMax=%RANDOM%
FOR %F IN (C:\temp\source\*.*) DO IF !SrcCount! LSS %SrcMax% (
SET /A SrcCount += 1
ECHO !SrcCount! COPY %F C:\temp\output
COPY %F C:\temp\output
)
(I'm assuming that your X is known beforehand – represented by the variable $x
in the following code).
Since you weren't adverse to a PowerShell solution:
Get-ChildItem SomeFolder | Get-Random -Count $x | Move-Item -Destination SomeOtherFolder
or shorter:
gci somefolder | random -c $x | mi -dest someotherfolder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With