lotirthos227
lotirthos227

Reputation: 327

Powershell - Create folder using a CSV file

I just created a little script that use a CSV file to batch create folder. But I saw some people doing the folder creation using a different way.

CSV:

folder
4.1.1 Process
4.1.2 Score card
4.1.3 Strategy
4.1.4 Governance
4.1.5 Master plan  Calendar
4.1.6 Budget follow up
4.1.7 Budget documentation
4.1.8 Benchmarkvision
4.1.9 Std Documentation
4.1.10 Layout
4.1.11 Project
4.1.12 Training
4.1.13 Team structure
4.1.14 Work shop
4.1.15 Tools
4.1.16 Problem solving
4.1.17 Presentation
4.1.18 Working data zone
4.1.19 meeting
4.1.20 S
4.1.21 Miscellenous

Script:

#change the $folderlist path as it's a hard link.
$folderlist = Import-Csv "C:\folders.csv"
$rootpath = read-host "Enter the path of the root folder where the csv files will be created"

foreach ($folder in $folderlist){
    $path = $rootpath+$folder.folder
    new-item -type directory -path $path
    } 

Quite simple, but I saw people use things like $(_$.folder) or other functions that I don't understand. Is there someone that can show me an other way to do it using $_ and %{ }?

I hope my question is clear if not I will give more information.

John

Upvotes: 1

Views: 10287

Answers (1)

alroc
alroc

Reputation: 28194

The only thing I think I would change (assuming that your input CSV is properly formatted) is how you're constructing your path.

foreach ($folder in $folderlist){
    $path = join-path -path $rootpath -childpath $folder.folder;
    new-item -type directory -path $path;
    } 

Alternate:

foreach ($folder in $folderlist){
    new-item -type directory -path $rootpath -name $folder.folder;
    }

Alternate 2 (derived from above):

$folderlist|foreach-object {new-item -type directory -path $rootpath -name $_.folder;}

Alternate 3 (derived from above):

$folderlist|foreach-object {new-item -type directory -path (join-path -path $rootpath -childpath $_.folder);}

% is an alias for foreach-object - I always use the expanded alias in scripts & explanations like this, to ensure that everything is crystal clear.

Edit: One more way that's even more concise and depending on the size of your CSV file, could be better on memory usage.

$rootpath = read-host "Enter the path of the root folder where the csv files will be created"
Import-Csv "C:\folders.csv"|foreach-object {new-item -type directory -path (join-path -path $rootpath -childpath $_.folder);}

Upvotes: 6

Related Questions