sens31
sens31

Reputation: 27

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:

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 }

Upvotes: 2

Views: 108

Answers (2)

Santiago Squarzon
Santiago Squarzon

Reputation: 59820

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$_") }
}

Combining the interpolated paths is also an alternative using this method, similar to ben's helpful answer, though this might less readable:

$initialPath = New-Item .\Project -ItemType Directory
1..3 | ForEach-Object {
    foreach($i in 1..2) {
        $null = $initialPath.CreateSubdirectory("Project$_\Phase$i")
    }
}

Upvotes: 3

ben
ben

Reputation: 51

this should do

foreach ($project in 1..3){foreach ($phase in 1..2) {new-item -Type Directory "C:\Projects\Project$($project)\Phase$($phase)"}}

Upvotes: 4

Related Questions