Building directory structure from csv with foreach

Copper Contributor

Hi Powershell community,

I am using the foreach function to build a directory structure that looks like this example (folders and subfolders, for each state, for each team)

 

 

Teams
    Kansas
        Wildcats  
            Documentation
                Stats
                Players
            Projects
            Forms

 

 

 

# Define buildPath
function buildPath($path)
{
If(!(test-path $path))
	{
		New-Item -Path $path -ItemType Directory -Force
	}
}

$csv = "C:\Example\Teams.csv"
$root = "C:\Example\Teams"


$States = (Import-Csv $csv).States
$Folders = (Import-Csv $csv).Folders
$Subfolders = (Import-Csv $csv).Subfolders

Write-Host $States

    foreach ($state in $States)
    {

Write-Host $state

        $Schools = (Import-Csv $csv).$state

Write-Host $Schools

        foreach ($school in $Schools)
        {

Write-Host $school

            foreach ($folder in $Folders)
            {

Write-Host $folder

#Create $folder(s) in $school directory
                $path = "$root\$state\$school\$folder"
                buildPath($path)
            }

#Create $subfolder(s) in "Documentation" directory            
            foreach ($subfolder in $Subfolders)
            {

Write-Host $subfolder
                $path = "$root\$state\$school\Documentation\$subfolder"
                buildPath($path)
            }
           
        }

    }

 

 

 

 

 

 

The problem is that the "Folders" and "Subfolders" are generating in the "Teams" directory and in the "State" directory, but not in the "School" directory, where they belong. 

 

My hypothesis is that the problem is in the path line, since it is generating the "Folders" at $root and $root\$state, instead of in the $root\$state\$school directories.

 

 

 

 

 

 

$path = "$root\$state\$school\$folder"

 

 

 

 

 

 

 

If foreach isn't the best way to approach this goal, I am also interested to hear other approaches. The csv is attached.

 

Thank you,

Annie

1 Reply

Hi @annieeby 

 

Can you please tell us the exact folder hierarchy you expect from your Teams.csv data sample. It will help us understand what you really need here. Maybe not only a script problem, but more a data one :)

 

Cheers

Cyrille