0

I know how to use New-Item in PowerShell so I can create some directories. But can I in anyway make this code shorter?

New-Item 'c:\drivers\Windows\Network\32bit PowerShell' -Type Directory
New-Item 'c:\drivers\Windows\Network\64bit PowerShell' -Type Directory
New-Item 'c:\drivers\Windows\Sound\32bit PowerShell' -Type Directory
New-Item 'c:\drivers\Windows\Sound\64bit PowerShell' -Type Directory
New-Item 'c:\drivers\Utility' -Type Directory
New-Item 'c:\drivers\Software' -Type Directory

As you can see I'm trying to create this directory tree:

C:\drivers
├─Windows
│ ├─Network
│ │ ├─32bit PowerShell
│ │ └─64bit PowerShell
│ └─Sound
│   ├─32bit PowerShell
│   └─64bit PowerShell
├─Utility
└─Software
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Thomas BP
  • 1,187
  • 3
  • 26
  • 62

2 Answers2

1

Make a list of paths and feed it into New-Item:

$folders = 'C:\drivers\Windows\Network\32bit PowerShell',
           'C:\drivers\Windows\Network\64bit PowerShell',
           ...

$folders | ForEach-Object {
    New-Item -Path $_ -Type Directory
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • A ForEach-Object can work, but it was all the directories/folder paths that I wonder, if there was any way too make shorter :-) If not then thx. for the solution. – Thomas BP Jan 06 '18 at 17:33
  • For the sample structure you've described I don't see a way to shorten that. Maybe put the list of paths in a file and read that file with `Get-Content`, but that's about it. – Ansgar Wiechers Jan 06 '18 at 18:10
  • Ditto on what Ansgar says. I like a challenge, so, I tried, and achieved the result you are after, but it took 27 lines of code (minus comments and line spaces) and I ended up with 2 ForEach and 2 If statements because if the needed brancing, which is far more complicated than the proposed options. – postanote Jan 07 '18 at 02:10
0

New-Item can consume multiple paths as list:

New-Item -ItemType Directory -Path `
'c:\drivers\Utility','c:\drivers\Software', `
'c:\drivers\Windows\Network\32bit PowerShell', `
'c:\drivers\Windows\Network\64bit PowerShell', `
'c:\drivers\Windows\Sound\32bit PowerShell', `
'c:\drivers\Windows\Sound\64bit PowerShell'
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 06 '22 at 14:29