PowerShell: Create Folders and Subfolders From an Excel List

Advertisement
Create folders and subfolders from an Excel list File Operations
Advertisement

Every new fiscal year I set up the same tree of folders: year, then department, then document type. The list already lives in Excel, yet I still end up right-clicking “New folder” dozens of times. A batch file got me part of the way, until a department called “Café” came out as “Caf├⌐”. On a work PC I can't install a folder-creation utility either.

So I wrote a small PowerShell tool instead. You copy the cells in Excel, paste them in, and it creates the whole nested structure. A row with blank cells on the left goes under the same folder as the row above, so the spreadsheet can stay the way people usually write it. You get a preview before anything is created, plus an Undo button.

The tool after creating folders from a list copied out of Excel
Three Excel columns pasted as they are, 12 folders created

Ways to create many folders at once

On Windows there are four common approaches. They all end up creating the same folders. What changes is the shape the list has to be in, and what happens when a name is bad.

Method List format Where it falls short
File Explorer by hand None Tedious past ten folders, typos creep in
Batch file (md) One md “Year\Dept\Docs” line per folder Accented letters get mangled. Building the lines from Excel needs a formula
PowerShell one-liner One “Year\Dept\Docs” path per line Excel columns can't be used directly
The tool in this post Copied Excel cells, an indented Notepad list, or paths You paste the script into PowerShell first

Every method creates the intermediate folders (“FY2026”, “01_Sales”) for you. Even md does this as long as command extensions are on, which is the default.

Why the batch file mangles folder names

I reproduced the usual setup. Build lines like these from the Excel list, paste them into Notepad, save as make.bat, then double-click it.

md "FY2026\01_Sales\Quotes"
md "FY2026\01_Sales\Invoices"
md "FY2026\02_Café\Menus"

The plain ASCII folders were fine. The one with “é” was not. Command Prompt printed this:

md "FY2026\02_Café\Menus"
Folders created by the batch file, one with a garbled name
"02_Café" became "02_Caf├⌐" (the drive labels are Japanese because this is a Japanese PC)

The cause is an encoding mismatch. Notepad saves as UTF-8 by default today, while Command Prompt reads a batch file using the console code page, which is 437 on a US English install. The two bytes UTF-8 uses for “é” are read as two separate characters, so the folder gets that name. Names in any language outside plain ASCII run into the same thing.

You can keep the batch file if you add “chcp 65001” as the first line, or save it as “ANSI” in Notepad. Building the lines is still extra work, though. A list with blank cells on the left needs a formula to carry the parent down, or you get lines like md “\\Invoices”. A name that contains “/” (say “Q4 review 12/15”) stops with an error.

If the list is already paths, a PowerShell one-liner is enough

When each line already looks like “Year\Dept\Docs”, you don't need the tool. Copy the list, then run this in PowerShell with $base changed to your target folder.

$base = "D:\Work\2026"
Get-Clipboard | Where-Object { $_.Trim() } | ForEach-Object { New-Item -ItemType Directory -Path (Join-Path $base $_.Trim()) -Force }

With the three lines below on the clipboard, it creates FY2026 with the department and document folders under it. Folders that already exist are left alone because of -Force. PowerShell handles text as Unicode internally, so the encoding problem above doesn't happen. It worked the same in PowerShell 5.1 and 7.

FY2026\01_Sales\Quotes
FY2026\01_Sales\Invoices
FY2026\02_HR\Timesheets

Copy three Excel columns instead and the same command goes wrong. Cells are separated by tabs, so a full row fails with “Illegal characters in path.” Rows that start with blank cells lose the leading tabs to Trim, and “Invoices”, “Contracts” and the rest land directly in $base with no hierarchy at all. To use the Excel list as it is, use the tool below.

The tool: create folders from an Excel list

Open PowerShell (5.1 or 7), paste the whole script, then press Enter to open the window. You don't need to run as administrator. To keep it as a .ps1 file, save it as “UTF-8 with BOM” so PowerShell 5.1 reads it correctly.

# Create nested folders in one go from a list (Excel cells / Notepad text), PowerShell 5.1 / 7
Add-Type -AssemblyName System.Windows.Forms, System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()

# Values shared with the button handlers (Created is used by Undo)
$app = @{ Created = New-Object System.Collections.ArrayList; Plan = @(); LoadedCsv = $false }

function Add-Ctl($ctl, $x, $y, $w, $h) {
    $ctl.Location = New-Object System.Drawing.Point($x, $y)
    $ctl.Size = New-Object System.Drawing.Size($w, $h)
    $form.Controls.Add($ctl)
    return $ctl
}

# Read a text file in the right encoding (BOM, then UTF-8, then the system ANSI code page)
function Read-ListFile($path) {
    $bytes = [IO.File]::ReadAllBytes($path)
    if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
        return [Text.Encoding]::UTF8.GetString($bytes, 3, $bytes.Length - 3)
    }
    if ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) {
        return [Text.Encoding]::Unicode.GetString($bytes, 2, $bytes.Length - 2)
    }
    try {
        $strict = New-Object System.Text.UTF8Encoding($false, $true)   # throws on invalid bytes
        return $strict.GetString($bytes)
    } catch {
        $ansi = [Globalization.CultureInfo]::CurrentCulture.TextInfo.ANSICodePage
        return [Text.Encoding]::GetEncoding($ansi).GetString($bytes)  # Notepad ANSI files, Excel CSV files
    }
}

# Split one CSV line into cells (commas inside quotes are kept)
function Split-CsvLine($line) {
    $cells = @(); $cur = ""; $q = $false
    for ($i = 0; $i -lt $line.Length; $i++) {
        $c = [string]$line[$i]
        if ($q) {
            if ($c -eq '"' -and $i + 1 -lt $line.Length -and [string]$line[$i + 1] -eq '"') { $cur += '"'; $i++ }
            elseif ($c -eq '"') { $q = $false }
            else { $cur += $c }
        } elseif ($c -eq '"') { $q = $true }
        elseif ($c -eq ',') { $cells += $cur; $cur = "" }
        else { $cur += $c }
    }
    $cells += $cur
    return , $cells
}

# Replace characters Windows does not allow / return the reason a name is invalid
$zen = @{ '<' = '('; '>' = ')'; ':' = '-'; '"' = "'"; '/' = '-'; '|' = '-'; '?' = ''; '*' = '' }
function Fix-Name($name) {
    if (-not $chkZen.Checked) { return $name }
    foreach ($k in $zen.Keys) { $name = $name -replace [regex]::Escape($k), $zen[$k] }
    return $name
}
function Test-Name($name) {
    if ($name -match '[<>:"/|?*\x00-\x1F]') { return "has a character Windows does not allow ( < > : "" / | ? * )" }
    if ($name.Trim('.') -eq "") { return "a name made only of periods is not allowed" }
    if ($name.EndsWith(".")) { return "Windows drops a trailing period" }
    if ($name -match '^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\..*)?$') { return "reserved name in Windows ( $name )" }
    return $null
}

# Turn the pasted list into the list of folders to create
#   - Tab-separated (copied from Excel): each column is a level. A blank cell on the left means "same as the row above"
#   - Indented with spaces (Notepad): deeper indent = deeper level
#   - Paths separated by "\": used as is
function Get-Plan {
    $base = $txtBase.Text.Trim().TrimEnd("\")
    $lines = $txtList.Text -split "\r?\n"
    $isCsv = $app.LoadedCsv
    $current = @(); $indents = @(); $seen = @{}; $items = New-Object System.Collections.ArrayList
    $start = 0; if ($chkHeader.Checked) { $start = 1 }
    for ($n = $start; $n -lt $lines.Count; $n++) {
        $line = $lines[$n]
        if ($line.Trim(" `t ") -eq "") { continue }
        $err = $null
        if ($isCsv) { $cells = Split-CsvLine $line }
        elseif ($line.Contains("`t")) {
            $cells = @($line -split "`t" | ForEach-Object { if ($_ -match '^".*"$') { ($_ -replace '^"|"$', '') -replace '""', '"' } else { $_ } })
        } else {
            # Turn the indent width (a full-width space counts as two) into a level number
            $body = $line.TrimStart("  "); $lead = $line.Remove($line.Length - $body.Length)
            $w = $lead.Length + ($lead.Split(' ').Count - 1)
            while ($indents.Count -gt 0 -and $indents[-1] -gt $w) { $indents = @($indents | Select-Object -SkipLast 1) }
            if ($indents.Count -eq 0 -or $indents[-1] -lt $w) { $indents += $w }
            $level = $indents.Count - 1
            $cells = @(@("") * $level) + @($body)
        }
        # Each cell can hold more levels separated by a backslash; trim the spaces
        $parts = @(); $first = -1
        for ($i = 0; $i -lt $cells.Count; $i++) {
            $c = $cells[$i].Trim(" `t ")
            if ($c -eq "") { if ($first -ge 0) { $parts += , $null } else { $parts += , "" }; continue }
            if ($first -lt 0) { $first = $i }
            $parts += , @($c -split '\\' | ForEach-Object { $_.Trim(" `t ") } | Where-Object { $_ -ne "" })
        }
        while ($parts.Count -gt 0 -and $null -eq $parts[-1]) { $parts = @($parts | Select-Object -SkipLast 1) }
        if ($first -lt 0) { continue }
        if ($cells[$first].Trim() -match '^([A-Za-z]:\\|\\\\)') { $err = "write the path below the target folder, not a full path" }
        if ($first -gt $current.Count) { $err = "two or more levels deeper than the row above (no parent folder)" }
        if ($parts -contains $null) { $err = "blank cell in the middle of the row" }
        $names = @()
        if (-not $err) {
            $names = @($current | Select-Object -First $first)
            for ($i = $first; $i -lt $parts.Count; $i++) { $names += $parts[$i] }
            $names = @($names | ForEach-Object { Fix-Name $_ })
            $current = $names
        }
        if ($err) {
            [void]$items.Add([pscustomobject]@{ Status = "Error"; Rel = $line.Trim(); Full = ""; Note = ("line {0}: {1}" -f ($n + 1), $err) }); continue
        }
        # List each folder from the parent down, skipping ones already listed
        $rel = ""; $parentErr = $null
        foreach ($nm in $names) {
            $rel = if ($rel) { $rel + "\" + $nm } else { $nm }
            $key = $rel.ToLowerInvariant()
            if ($seen.ContainsKey($key)) { if ($seen[$key].Status -eq "Error") { $parentErr = $true }; continue }
            $full = Join-Path $base $rel
            $why = Test-Name $nm
            if (-not $why -and $parentErr) { $why = "parent folder has an error" }
            if (-not $why -and $full.Length -ge 248) { $why = "path too long ({0} characters)" -f $full.Length }
            if (-not $why -and (Test-Path -LiteralPath $full -PathType Leaf)) { $why = "a file with the same name exists" }
            if ($why) { $st = "Error"; $parentErr = $true }
            elseif (Test-Path -LiteralPath $full -PathType Container) { $st = "Exists" }
            else { $st = "New" }
            $it = [pscustomobject]@{ Status = $st; Rel = $rel; Full = $full; Note = $(if ($why) { "line {0}: {1}" -f ($n + 1), $why } else { "" }) }
            $seen[$key] = $it; [void]$items.Add($it)
        }
    }
    return , $items.ToArray()
}

function Show-Plan {
    $lv.BeginUpdate(); $lv.Items.Clear()
    foreach ($it in $app.Plan) {
        $row = New-Object System.Windows.Forms.ListViewItem($it.Status)
        [void]$row.SubItems.Add($it.Rel); [void]$row.SubItems.Add($it.Note)
        if ($it.Status -eq "Error") { $row.ForeColor = [System.Drawing.Color]::Firebrick }
        elseif ($it.Status -eq "Exists") { $row.ForeColor = [System.Drawing.Color]::Gray }
        elseif ($it.Status -eq "Created") { $row.ForeColor = [System.Drawing.Color]::SeaGreen }
        [void]$lv.Items.Add($row)
    }
    $lv.EndUpdate()
    $c = @{}; foreach ($s in "New", "Exists", "Error", "Created") { $c[$s] = @($app.Plan | Where-Object { $_.Status -eq $s }).Count }
    $lblInfo.Text = "New {0} / Exists {1} / Error {2} / Created {3}" -f $c["New"], $c["Exists"], $c["Error"], $c["Created"]
    $btnMake.Enabled = ($c["New"] -gt 0)
}

function Invoke-Check {
    $base = $txtBase.Text.Trim()
    if (-not (Test-Path -LiteralPath $base -PathType Container)) { $lblInfo.Text = "Target folder not found"; $btnMake.Enabled = $false; return $false }
    $app.Plan = Get-Plan
    Show-Plan
    return $true
}

function Invoke-Make {
    if (-not (Invoke-Check)) { return }             # check again right before creating
    foreach ($it in $app.Plan) {
        if ($it.Status -ne "New") { continue }
        try {
            [void][IO.Directory]::CreateDirectory($it.Full)
            $it.Status = "Created"; [void]$app.Created.Add($it.Full)
        } catch { $it.Status = "Error"; $it.Note = $_.Exception.Message }
    }
    Show-Plan
    $btnUndo.Enabled = ($app.Created.Count -gt 0)
}

# Delete the folders this tool created, deepest first. Folders that are not empty are kept
function Invoke-Undo {
    $kept = 0; $removed = 0
    foreach ($p in @($app.Created | Sort-Object { $_.Length } -Descending)) {
        if (-not (Test-Path -LiteralPath $p -PathType Container)) { $app.Created.Remove($p); continue }
        if (@(Get-ChildItem -LiteralPath $p -Force).Count -gt 0) { $kept++; continue }
        Remove-Item -LiteralPath $p; [void]$app.Created.Remove($p); $removed++
    }
    [void](Invoke-Check)
    $lblInfo.Text = "Undo done: removed {0} / kept {1} (not empty)" -f $removed, $kept
    $btnUndo.Enabled = ($app.Created.Count -gt 0)
}

$font = New-Object System.Drawing.Font("Segoe UI", 10)
$form = New-Object System.Windows.Forms.Form
$form.Text = "Create Folders From a List"
$form.ClientSize = New-Object System.Drawing.Size(1160, 600)
$form.Font = $font
$form.StartPosition = "CenterScreen"

$l1 = Add-Ctl (New-Object System.Windows.Forms.Label) 12 10 440 22
$l1.Text = "Folder list (paste Excel cells / a Notepad list)"
$txtList = Add-Ctl (New-Object System.Windows.Forms.TextBox) 12 34 440 430
$txtList.Multiline = $true; $txtList.ScrollBars = "Both"; $txtList.WordWrap = $false; $txtList.MaxLength = 0
$txtList.Font = New-Object System.Drawing.Font("Consolas", 10)
$txtList.add_TextChanged({ $btnMake.Enabled = $false; $app.LoadedCsv = $false })

$btnLoad = Add-Ctl (New-Object System.Windows.Forms.Button) 12 472 200 30
$btnLoad.Text = "Load from file..."
$btnLoad.add_Click({
    $dlg = New-Object System.Windows.Forms.OpenFileDialog
    $dlg.Filter = "List files (*.txt;*.csv;*.tsv)|*.txt;*.csv;*.tsv|All files (*.*)|*.*"
    if ($dlg.ShowDialog() -eq "OK") {
        $txtList.Text = Read-ListFile $dlg.FileName
        $app.LoadedCsv = ([IO.Path]::GetExtension($dlg.FileName) -eq ".csv")
        [void](Invoke-Check)
    }
})
$chkHeader = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 230 474 230 26
$chkHeader.Text = "Skip the first row (headers)"
$chkZen = Add-Ctl (New-Object System.Windows.Forms.CheckBox) 12 506 440 26
$chkZen.Text = "Replace characters Windows does not allow ( / : * ? etc.)"; $chkZen.Checked = $true
foreach ($chk in $chkHeader, $chkZen) { $chk.add_CheckedChanged({ if ($txtList.Text.Trim()) { [void](Invoke-Check) } }) }

$l2 = Add-Ctl (New-Object System.Windows.Forms.Label) 470 10 300 22
$l2.Text = "Create the folders in"
$txtBase = Add-Ctl (New-Object System.Windows.Forms.TextBox) 470 34 590 26
$txtBase.Text = [Environment]::GetFolderPath("MyDocuments")
$btnBase = Add-Ctl (New-Object System.Windows.Forms.Button) 1066 33 82 28
$btnBase.Text = "Browse..."
$btnBase.add_Click({
    $dlg = New-Object System.Windows.Forms.FolderBrowserDialog
    if (Test-Path -LiteralPath $txtBase.Text) { $dlg.SelectedPath = $txtBase.Text }
    if ($dlg.ShowDialog() -eq "OK") { $txtBase.Text = $dlg.SelectedPath; [void](Invoke-Check) }
})

$lv = Add-Ctl (New-Object System.Windows.Forms.ListView) 470 70 678 394
$lv.View = "Details"; $lv.FullRowSelect = $true
[void]$lv.Columns.Add("Status", 70); [void]$lv.Columns.Add("Folder", 250); [void]$lv.Columns.Add("Note", 350)

$lblInfo = Add-Ctl (New-Object System.Windows.Forms.Label) 470 472 678 26
$lblInfo.Text = "Paste a list, then click Preview"

$btnCheck = Add-Ctl (New-Object System.Windows.Forms.Button) 470 506 110 34
$btnCheck.Text = "Preview"
$btnCheck.add_Click({ [void](Invoke-Check) })
$btnMake = Add-Ctl (New-Object System.Windows.Forms.Button) 586 506 130 34
$btnMake.Text = "Create folders"; $btnMake.Enabled = $false
$btnMake.add_Click({ Invoke-Make })
$btnUndo = Add-Ctl (New-Object System.Windows.Forms.Button) 722 506 110 34
$btnUndo.Text = "Undo"; $btnUndo.Enabled = $false
$btnUndo.add_Click({ Invoke-Undo })
$btnOpen = Add-Ctl (New-Object System.Windows.Forms.Button) 838 506 90 34
$btnOpen.Text = "Open"
$btnOpen.add_Click({ if (Test-Path -LiteralPath $txtBase.Text) { Start-Process explorer.exe -ArgumentList ('"' + $txtBase.Text + '"') } })

$lNote = Add-Ctl (New-Object System.Windows.Forms.Label) 12 548 1136 44
$lNote.Text = "Each Excel column is one level. A row whose left cells are blank goes under the same folder as the row above. In Notepad, indent with spaces or separate levels with \ (Sales\Quotes). Existing folders are left alone. Undo removes only the empty folders this tool created."

[void]$form.ShowDialog()

Feel free to use and modify the script.

List formats it accepts

Format Example How levels are decided
Cells copied from Excel Column A = year, B = department, C = documents Each column is a level. Blank cells on the left mean “same as the row above”
Indented Notepad list Two spaces before a department, four before a document folder Deeper indent means a deeper level
Paths with “\” FY2026\01_Sales\Quotes Split on “\”. Works inside an Excel cell too
Load from file .txt, .csv, .tsv Same rules. A .csv is read as comma-separated

Files are read as UTF-8 (with or without a BOM), UTF-16, or the system ANSI code page, which covers what Notepad's “ANSI” option and Excel's CSV export produce.

Buttons and options

Item What it does
Skip the first row (headers) Turn on when row 1 holds headings like “Year” or “Department”
Replace characters Windows does not allow Turns “/” and “:” into “-”, and drops “?” and “*”. When off, that row is an error
Create the folders in Starts at Documents. Browse to pick another folder, a network share works too
Preview Lists every folder it will create, marked New, Exists, or Error
Create folders Creates only the New ones. Editing the list after a preview disables it until you preview again
Undo Removes the folders this tool created. Folders that now contain files are kept

Existing folders show as “Exists” and are not touched. Nothing inside them is deleted or overwritten.

Trying it out

Pasting the Excel list as it is

The list has three columns: year, department, documents. Cells that repeat the row above are left blank. That's easy to read, but neither a batch file nor the one-liner can take it directly.

An Excel folder list in three columns: year, department, documents
Repeated year and department cells are left blank

I copied A1:C9 and pasted it into the box on the left, then turned on “Skip the first row” and clicked Preview. Twelve folders appeared on the right, with the blank cells filled in from the rows above, as in “FY2026\02_HR\Onboarding”.

The preview after pasting the list
Every folder that will be created is listed before anything happens

Clicking “Create folders” turned all twelve into “Created” (the first screenshot). In a folder picker they show up three levels deep.

The folder tree created by the tool
Names match the Excel list exactly

Previewing the same list again shows all twelve as “Exists”, and “Create folders” stays disabled. Next year you can change the year in the sheet and reuse it without duplicating anything.

A Notepad list with names Windows rejects

Next I loaded an indented Notepad list with a few problem names mixed in: “Q4 review 12/15”, the reserved name “CON”, and “Minutes.” with a trailing period.

Preview of a list that contains invalid names
The slash is replaced, CON and "Minutes." are flagged in red

“Q4 review 12/15” became “Q4 review 12-15” and is ready to create. CON and “Minutes.” show as errors with the reason and line number. The rest of the folders can still be created.

Undoing what was created

Undo is there for when you picked the wrong target folder. To test it, I created folders, dropped a file into “Timesheets”, then clicked Undo.

The tool after clicking Undo
The folder with a file in it, plus its parents, stayed. The rest were removed

The empty folders were removed. “Timesheets” and its parents “02_HR” and “FY2026” stayed. Undo only touches folders created since the tool was opened, never ones that were there before. Closing the tool clears that record.

Things that tripped me up

The first version wouldn't start in PowerShell 5.1

PowerShell 7 ran it fine, but 5.1 stopped with a parse error before the window even opened. The culprit was “line {0}: {1}” -f ($n + 1), $err inside a [pscustomobject]@{ } literal. PowerShell 5.1 treats that comma as an argument separator rather than part of the -f expression. Wrapping the whole -f expression in parentheses fixed it for both. Many work PCs only have 5.1, so test on both.

Names Windows won't create, or quietly changes

CON, NUL, COM1 and a few others are reserved, so you can't use them as folder names. A trailing period or space gets silently removed, which means “Minutes.” would become “Minutes” and no longer match your list. The tool flags these before creating anything, and trims stray spaces around Excel cells. Paths of 248 characters or more are also flagged, since folder creation can fail there.

Commas inside CSV cells

When Excel saves a CSV, a cell such as “02_HR, Payroll” gets wrapped in quotes. Splitting naively on commas would turn it into two folders, so commas inside quotes are not treated as separators.

Related posts

To list what ends up inside those folders, see exporting a file list to CSV for Excel. To tidy up file names in bulk, see bulk renaming files with an undo log. To turn the Excel files you collect into PDFs, see batch converting Excel files to PDF.

Summary

  • Batch files mangle accented names because Notepad saves UTF-8 while Command Prompt reads the console code page
  • A list of “\” paths only needs a PowerShell one-liner
  • For an Excel list with blank cells, paste it into the tool above. It previews, creates, and can undo

References

Comments

Copied title and URL