Piping values to New-Item to create directories in PowerShell

独自空忆成欢 提交于 2019-12-11 12:23:24

问题


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.


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/29203286/piping-values-to-new-item-to-create-directories-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!