Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create 2 child directories inside 3 different child directories

I’m trying to write a simple script that will create a folder and then 3 different folders inside and once that is done each of those 3 different folders should have 2 child folders named ‘Phase’ (1..2).

I’m trying to loop through the path, i.e the child folders (Project) but I don’t know how to implement it, otherwise I can just write the last foreach loop another 3 times but that would be inconsistent.

The structure should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

C:\Projects\Project1\Phase1
C:\Projects\Project1\Phase2
C:\Projects\Project2\Phase1
C:\Projects\Project2\Phase2
C:\Projects\Project3\Phase1
C:\Projects\Project3\Phase2

The script so far I’ve written is:

# Path variable 

$PhasePath = "C:\Projects\Project1"

# Creating the main directory
mkdir C:\Projects

# Loop from 1-3 and create a subdirectory in - Path C:\Projects using the path variable
1..3 | foreach $_{ New-Item -ItemType directory -Name $("Project" + $_) -Path C:\Projects } 

1..2 | foreach $_{ New-Item -ItemType directory -Name $("Phase" + $_) -Path $PhasePath }

>Solution :

Here is one way to do it using the instance method CreateSubdirectory from the DirectoryInfo class:

$initialPath = New-Item C:\Projects\ -ItemType Directory
1..3 | ForEach-Object {
    $sub  = $initialPath.CreateSubdirectory("Project$_")
    $null = 1..2 | ForEach-Object { $sub.CreateSubdirectory("Phase$_") }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading