Simon Elms
Simon Elms

Reputation: 19628

Piping values to New-Item to create directories in PowerShell

I've got a directory, C:\temp\test\, containing three DLL's I've called First.dll, Second.dll, Third.dll. I want to create sub-directories named after each of the DLL's.

This is what I've tried so far:

$dirName = "Tenth"
new-item $dirName -ItemType directory

That works. It created a sub-directory called "Tenth".

This also works:

(get-childitem -file).BaseName | select $_

It returns:

First
Second
Third

I've checked the type of the output from that command and it tells me "select $_" is of type System.String.

Now the bit that doesn't work:

(get-childitem -file).BaseName | new-item -Name $_ -ItemType directory

I get the following error repeated three times:

new-item : An item with the specified name C:\temp\test already exists.
At line:1 char:34
+ (get-childitem -file).BaseName | new-item -Name $_ -ItemType directory
+                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (C:\temp\test:String) [New-Item], IOException
    + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand

The current folder I'm executing the commands from is C:\temp\test\ .

I haven't been able to find any similar examples on the Internet to show me where I'm going wrong. Can anyone give me any pointers? Cheers.

Upvotes: 2

Views: 5622

Answers (3)

Cid
Cid

Reputation: 15247

New-Item accepts the parameter -Path to be piped and it can be an array of strings.

Then, you can create an object with a property Path that contains all the needed folders to be created

<#
 # a simple array as example,
 # but it could be the result of any enumerable,
 # such as Get-ChildItem and stuff
 #>
$FoldersToCreate = @('a', 'b', 'c')

# creates the folders a, b and c at the current working directory
[PSCustomObject]@{ Path = $FoldersToCreate } | New-Item -ItemType Directory

Or, alternatively :

$FoldersToCreate |
    Select-Object @{ name = "Path"; expression = { "c:\testDir\$_" } } |
    New-Item -ItemType Directory

Upvotes: 2

user4018458
user4018458

Reputation:

Now the bit that doesn't work:

(get-childitem -file).BaseName | new-item -Name $_ -ItemType directory

This way, it works and doesn't need the ForEach-Object:

(dir -file).BaseName|ni -name{$_} -ItemType directory -WhatIf

Upvotes: 2

Bluecakes
Bluecakes

Reputation: 2149

$_ references each item as it comes along the pipeline so you will need to pipe to ForEach-Object for your line to work, like this:

(get-childitem -file).BaseName | ForEach-Object {new-item -Name $_ -ItemType directory}

This will create the item in the current powershell directory, you can also specify -Path if you want to create the folders somewhere else.

(get-childitem -file).BaseName | ForEach-Object {new-item -Name $_ -Path C:\MyFolder -ItemType directory}

Upvotes: 1

Related Questions