Creating multiple folders using Powershell

11,464

Solution 1

For you definition of $users either put the variable inside the quotes or do the string concatenation in a subexpression e.g. $(). Also you had an extra space in the ItemType Parameter:

$local = "C:\Temp\Test"
$Users = "$local\AAA\","$local\BBB\","$local\CCC\"
New-Item -ItemType directory $Users

Solution 2

BenH's helpful answer offers an effective solution.

Why your command didn't work:

Your problem was one of operator precedence:

$local+"\AAA\",$local+"\BBB\",$local+ "\CCC\"

was interpreted as:

$local + ("\AAA\",$local) + ("\BBB\",$local) +"\CCC\"

resulting in a single string rather than the desired array, because the LHS - $local is a string.

Perhaps surprisingly, ,, the array-construction operator, has higher precedence than + - see Get-Help about_Operator_Precedence.


Therefore, using (...) for precedence would have made your command work:

$Users = ($local+"\AAA\"), ($local+"\BBB\"), ($local+"\CCC\")

Using expandable (interpolating) strings (inside "..."), as in BenH's answer, is more concise, but still:

  • requires defining auxiliary variable $local first

  • requires referencing $local in each expandable (interpolating) string ("...")


A DRY alternative is (% is an alias for ForEach-Object):

$Users = 'AAA', 'BBB', 'CCC' | % { "C:\Temp\$_\" }

Note that using a pipeline to achieve this is somewhat slow, but that won't matter in most cases.


Using the foreach statement is a little more verbose, but performs better:

$Users = foreach($name in 'AAA', 'BBB', 'CCC') { "C:\Temp\$name\" }
Share:
11,464
Novice_Techie
Author by

Novice_Techie

Updated on June 05, 2022

Comments

  • Novice_Techie
    Novice_Techie almost 2 years

    I need to create 3 folders named AAA,BBB,CCC at location :c\temp\test

    I tried the below codes:

    $local = "C:\Temp\Test"
    $Users = $local+"\AAA\",$local+"\BBB\",$local+"\CCC\"
    New-Item -Item Type directory $Users
    

    It is giving me error New-Item : A positional parameter cannot be found that accepts argument

    I also tried

    $local = "C:\Temp\Test"
    $Users = $local+"\AAA\",$local+"\BBB\",$local+"\CCC\"
    md $Users
    

    what am I missing here??