Windows – How to create multiple folders and name them by reading lines from text file

batchbatch filescriptshell-scriptwindows

I have a plain text file named Export.txt. It contains a list of geographical places, preceeded by a 3 digit number with leading zeros.


001 Aberdeen
002 Bellevue
003 Camas
004 Davenport
005 Edgewood
006 Ferndale
007 George
008 Harrington
009 Ilwaco
010 Kahlotus

How can I write a script or a batch file that would read each line from the file and create a folder with this name on a given location of an NTFS partition?

Note! Please note that the folder names must include the digits. Think of the list above as the actual list of folders.

Update! My actual list of folders to create is 245, ranging from 001 to 245. Here are the first few lines.

001 Harberget
002 Långflon
003 Källegrafsrös
004 Badstuknappen
005 Aspberget
006 Knipen
007 Halsjön
008 N Finnskoga
009 Båtstad
010 Tisjön

245 Milskär

The complete list can be found here:

The PS script provided by Martin is not working well with characters like Å, Ä and Ö. It only creates 116 folders out of the total 245 found in the text file. It skips every line that includes either one of these characters. So it skips 002 Långflon and 003 Källegrafsrös for instance, but it creates 001 Harberget and 004 Badstuknappen.

Best Answer

Here's a Powershell script that does what you want.

$folder="X:\Test";             # Directory to place the new folders in.
$txtFile="X:\Test\Export.txt"; # File with list of new folder-names
$pattern="\d+.+";              # Pattern that lines must match      

get-content $txtFile | %{

    if($_ -match $pattern)
        mkdir "$folder\$_";

This will include the digits in the name.

To run the script, do the following.

  1. Run Powershell as administrator.
  2. Type in Set-ExecutionPolicy RemoteSigned and press Enter to enable running of scripts. Press Y when prompted.
  3. Close Powershell.
  4. Copy and paste the script above into Notepad or Notepad++.
  5. Replace X:\Test with the absolute path to the location where you want to create your new folders.
  6. Replace X:\Test\Export.txt with the absolute path to the text file that contains the names you want to use for these folders.
  7. Replace \d+.+ with the pattern the lines must match. \d+ matches any number .+ matches any character.
  8. Save it as "FileName.ps1" or whatever name you want. Just make sure to keep the .ps1 extension.
  9. Open Windows Explorer and go to the location where you saved your ps1 file. Right click on it and select "Run with Powershell".


a b c d