Home > Software design >  Create 2 child directories inside 3 different child directories
Create 2 child directories inside 3 different child directories

Time:07-18

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 }

CodePudding user response:

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

CodePudding user response:

this should do

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