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

5

3

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.

Example

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

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.

--START OF FILE--
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
--END OF FILE--

The complete list can be found here: http://pastebin.com/SNde4bBN

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.

Samir

Posted 2014-02-27T13:47:37.687

Reputation: 17 919

I realize this is probably way to late for you, but the reason some of the names doesn't work correctly is because of the file's encoding. I downloaded your list of names, opened it in Notepad++ and clicked "Encoding" then "Convert to ANSI" and it worked right away. – Martin – 2016-02-02T18:55:35.953

Do you want the folder name to include the digits too? – and31415 – 2014-02-27T14:13:17.710

That is correct. – Samir – 2014-02-27T14:14:59.077

The list above was just a short example. My actual list of folders to create is 245, from 001 to 245. That's a lot of folders! It doesn't even end there. I will have to create a second, a third and a fourth parent folder and then create subfolders within these, ranging from 001 to 120, 001 to 200, etc. and ad infinitum. So I will re-use these scripts several times. Since I have the names that these folders need to have stored in a text file, this will greatly help me load off some of the manual work I need to do. So I greatly appreciate this guys. Thanks! – Samir – 2014-02-27T20:50:29.957

I've since updated my original answer to provide additional information to chew on. – and31415 – 2014-03-01T15:54:28.777

Answers

7

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".

Screenshots...

a b c d

Martin

Posted 2014-02-27T13:47:37.687

Reputation: 1 237

I'm on Windows 8 and it looks like Windows 8 comes with Powershell. So that's good. Just how do I run the script, can you be more specific please? – Samir – 2014-02-27T14:14:23.247

Will this include the digits in the folders name? – Samir – 2014-02-27T14:15:29.190

On what Windows version have you tested this? Also, what version of Powershell were you running? – Samir – 2014-02-27T19:09:38.797

Tested on Windows 7 running Powershell 2.0, you getting errors? – Martin – 2014-02-27T19:11:04.850

I am not at the Windows 8 computer now. I'm on Vista Ultimate 64-bit now. How do you check Powershell version? Mine says "Copyright (C) 2009" but I don't know what version it is. – Samir – 2014-02-27T19:12:01.697

Also, do I run regular "powershell" or "powershell ise" or "powershell modules"? – Samir – 2014-02-27T19:13:30.123

The command Set-ExecutionPolicy RemoteSigned produces red error message. And running "powershell modules" produces a yellow error message. WARNING: File C:\Windows\system32\WindowsPowerShell\v1.0\Modules\PSDiagnostics\PSDiagnostics.psm1 cannot be loaded because the execution of scripts is disabled on this system. – Samir – 2014-02-27T19:15:08.523

run the one that says "Windows PowerShell", to see version type; $PSVersionTable.PSVersion in powershell console, – Martin – 2014-02-27T19:15:30.057

you must right click on powershell and select run as administrator – Martin – 2014-02-27T19:16:11.293

Major 2 Minor 0 Build -1 Revision -1 – Samir – 2014-02-27T19:16:33.293

Yeah, I was right clicking on it and selecting run as admin. It says "Administrator" in the title bar. Strange... But it's OK now, I got it activated now, it worked the second time. – Samir – 2014-02-27T19:20:50.040

let us continue this discussion in chat

– Samir – 2014-02-27T19:21:10.383

I'm back on Windows 8 and this is not working. I can't run it from PS console window with admin elevation, or I dont' know how to. Just typing in script.ps1 and Enter doesn't help, suggested .\script.ps1 but it didn't work either. And running it by right clicking on the script file at location and then "Run with Powershell" prompts to enable script, even though I already used the elevated PS window to enable it with Set-ExecutionPolicy RemoteSigned. So pressing Y key to enable it (again) then produces an error which I can't read because the window closes. Any ideas? – Samir – 2014-02-28T08:08:49.777

Your new script works as expected now, even for a Windows 8 computer. Thumbs (and vote) up! Thanks! – Samir – 2014-02-28T13:21:14.633

I don't mean to bore you with this anymore. But yes, your new script is working. However, it works from C:\test and it works from Z:\test but it does not work from Z:\S_Värmland\test. The C is my local disk drive, and Z is the file server \\FILESERVER mounted as a network location. Let me guess, it doesn't like the Ä in the search path? – Samir – 2014-02-28T13:40:38.267

5

Batch / VBS hybrid solution

Tested with Windows XP SP3, Vista SP2 and Windows 7 SP1. It's a specially crafted batch script with an embedded VB Script which does the actual job. This way you get a script which should be compatible with any operating system released after XP SP2. The main credit goes to jeb and dbenham who come up with (and refined) the hybrid technique used here.

REM^ &@echo off>nul
REM^ &if "%~2" == "" exit /b 2
REM^ &pushd "%~2"
REM^ &cscript //e:vbscript //nologo "%~f0" "%~1"
REM^ &popd
REM^ &exit /b

Dim stream, text, lines, fso
Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2
stream.Charset = "utf-8"
stream.LoadFromFile Wscript.Arguments(0)
text = stream.ReadText
stream.Close

lines = Split(text, vbCrLf)
Set fso = CreateObject("Scripting.FileSystemObject")

For i = 0 To UBound(lines)
fso.CreateFolder(lines(i))
Next

Instructions

  1. Copy and paste the script above into Notepad or any other plain text editor (e.g. Notepad++).

  2. Save it as CreateFolders.cmd or whatever name you want. Just make sure to keep the .cmd extension.

  3. Open a command prompt and navigate to the folder where you saved the file:

    cd /d "X:\Folder\containing\CreateFolders.cmd"
    
  4. Run the batch script by specifying the list file and the destination folder as the first and second parameter, respectively:

    CreateFolders.cmd "X:\Some\folder\Export.txt" "X:\Destination\folder"
    

Screenshots

b c

References


PowerShell solution

The following PowerShell script replicates the solution above. It accepts two parameters, the first being the list file (which is assumed to be saved as UTF-8), and the second is the destination folder. Tested with Windows XP SP3, Vista SP2 and Windows 7 SP1.

Note Windows PowerShell 2.0 is bundled with Windows 7, but needs to be manually installed in XP/Vista. As for Windows XP, you need to have .NET Framework 2.0 SP1/SP2 installed, or .NET Framework 3.5 SP1, which include .NET Framework 2.0 SP2. Windows 8 and Windows 8.1 include PowerShell 3.0 and 4.0, respectively.

if ($args.Count -gt 1)
{
    $file=$args[0];
    $dest=$args[1];
    Get-Content $file -Encoding UTF8 | %{ md "$dest\$_" >$null; }
}

Instructions

  1. Copy and paste the script above into Notepad or any other plain text editor (e.g. Notepad++).

  2. Save it as CreateFolders.ps1 (or any other name, as long as you keep the proper extension).

  3. To run the script you can launch PowerShell and then either:

    • Navigate to the actual path, and then execute it:

      cd "C:\Some folder"
      & ".\CreateFolders.ps1" "X:\Some\folder\Export.txt" "X:\Destination\folder"
      
    • Execute it by specifying the full path directly:

      & "C:\Some folder\CreateFolders.ps1" "X:\Some\folder\Export.txt" "X:\Destination\folder"
      

    & is the call operator.

    As an alternative you can start it from a regular command prompt:

    powershell -ExecutionPolicy Bypass -NoLogo -NoProfile -File "C:\Some folder\CreateFolders.ps1" "X:\Some\folder\Export.txt" "X:\Destination\folder"
    

References


Previous (kind of working) solutions

Warning! Do not use them unless you known in advance the targeted system, and the data you're dealing with. If you still want to, make sure they work as expected.

Batch script

The following script will loop through all the lines of the list file and create as many folders, naming them after the actual line content. The script accepts two parameters: the first one is the path where the list is stored, which is hard-coded as Export.txt (feel free to put a different file name, but avoid spaces); the latter is the destination folder.

@echo off
setlocal

REM make sure there are enough parameters
if "%~2" == "" exit /b 2

REM set the working directory
pushd "%~1"

REM loop through the list and create the folders
for /f "delims=" %%G in (Export.txt) do (md "%~2\%%~G")

REM restore the working directory and exit
popd
endlocal & exit /b

Known limitations

  • Either ASCII or ANSI input files only.

Batch script - alternate UTF-8 version

This script is similar to the above one, but in this case the text file is not read directly but parsed through the type command output. The chcp is required first in order to change the encoding to UTF-8. In this case the list is not hard-coded but has to be specified as part of the first parameter. The second parameter is the destination folder.

@echo off
setlocal

REM make sure there are enough parameters
if "%~2" == "" exit /b 2

REM set the working directory
pushd "%~2"

REM set the list file
set file="%~1"

REM set the encoding to UTF-8
chcp 65001 >nul

REM loop through the list and create the folders
for /f "delims=" %%G in ('type %file%') do (md "%%~G")

REM restore the working directory and exit
popd
endlocal & exit /b

Known limitations

  • On English locales, the chcp 65001 command will halt the batch script execution, thus skipping any other command.

and31415

Posted 2014-02-27T13:47:37.687

Reputation: 13 382