Help w/ CSV Parsing

Hi Everyone,

I'm working through a test to see how CSV parsing in relation to folder and subfolder creation works. The script I have is as follows:

$File = "C:\Projects\Folders\folders.csv"
$Data = Import-Csv $File
$Base = "C:\Projects\Folders\Test\"
foreach($line in $Data) {
    $topFolder = $Base + $line.Base
    if (!(Test-Path $topFolder)) {
        New-Item $topFolder -type directory
    }
	if (!(Test-Path "$topFolder\$line.Sub2")) {
		New-Item "$topFolder\$line.Sub2" -type directory
	}
	if (!(Test-Path "$topFolder\$line.Sub2\$line.Sub3")) {
		New-Item "$topFolder\$line.Sub2\$line.Sub3" -type directory
	}
}
Write-Host "Folder created"

And the CSV looks like this:

Base,Sub1,Sub2
Folder 1, Subfolder 1,Subfolder 2

Now, I'm getting the CSV read just fine, however I'm getting stuck on building out the subsequent subfolders and end up with a "Folder 1" directory in my $Base which then gets populated with directories that look as such:

C:\Projects\Folders\Test\Folder 1\@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub1\@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub2

@{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub1 being the name of the first folder in the topmost folder (Folder 1)

and @{Base=Folder 1; Sub1=Subfolder 1; Sub2=Subfolder 2}.Sub2 being the nested folder within that subfolder.

What am I doing wrong here? I need the script to parse the CSV, create the "Base" folder, then populate the subfolder structure from Sub1 under that and then in each of those Sub1 folders I need to populate the directory structure with the folder names from Sub2.

It seems pretty straightforward but I'm obviously missing something.

February 6th, 2015 10:43pm

Why?

Just use the whole path and all subfolders willbe created:

new-item -ItemType Directory -Path c:\test\sub1\sub2\sub3

Hey - this ain't DOS and it ain't a Mac.  It is PowerShell.  No more dumb toaster here.

Free Windows Admin Tool Kit Click here and download it now
February 6th, 2015 11:13pm

jrv is right, but in case you really want to do it this way for some reason, your issue is that you need to add some dollar signs and parentheses in a few places. When you are doing string interpolation on an object property, you have to enclose the expression in $() because PowerShell won't normally assume that a period is part of your variable name. For example:

Test-Path "$topFolder\$line.Sub2"

needs to be:

Test-Path "$topFolder\$($line.Sub2)"
February 7th, 2015 12:04am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics