【问题标题】:Piping values to New-Item to create directories in PowerShell管道值到 New-Item 以在 PowerShell 中创建目录
【发布时间】:2022-02-25 15:18:43
【问题描述】:

我有一个目录 C:\temp\test\,其中包含三个我称为 First.dll、Second.dll、Third.dll 的 DLL。我想创建以每个 DLL 命名的子目录。

这是我迄今为止尝试过的:

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

这行得通。它创建了一个名为“Tenth”的子目录。

这也有效:

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

返回:

First
Second
Third

我检查了该命令的输出类型,它告诉我“select $_”的类型是 System.String。

现在不起作用的位:

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

我得到以下错误重复三遍:

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

我正在执行命令的当前文件夹是C:\temp\test\

我无法在 Internet 上找到任何类似的示例来告诉我哪里出错了。任何人都可以给我任何指示吗?干杯。

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    现在不起作用的位:

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

    这样,它可以工作并且不需要ForEach-Object

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

    【讨论】:

    • 很好,谢谢。你能解释一下为什么 $_ 周围需要大括号 {} 吗?
    • 这是 PowerShell 语法的一部分,将管道对象引用到接受管道输入的参数。例如,ForEach-Object 和 Where-Object 也需要花括号(但从 v3 开始,它们都获得了额外的新语法)
    【解决方案2】:

    $_ 引用管道中的每个项目,因此您需要通过管道连接到 ForEach-Object 以使您的线路正常工作,如下所示:

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

    这将在当前powershell目录中创建项目,如果你想在其他地方创建文件夹,你也可以指定-Path

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

    【讨论】:

    • 工作就像一个魅力。谢谢。
    【解决方案3】:

    New-Item 接受要通过管道传输的参数-Path,它可以是字符串数组。

    然后,您可以创建一个具有属性Path 的对象,其中包含所有需要创建的文件夹

    <#
     # 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
    

    或者,或者:

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

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 2018-09-13
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多