【问题标题】:Trying to create directories with Powershell尝试使用 Powershell 创建目录
【发布时间】:2016-05-24 10:49:20
【问题描述】:

我正在尝试在某个目标位置创建目录,如果它们不存在的话。

目录的名称来自另一个源位置。

对于C:\some\location中的每个目录名称
C:\another\location.新建同名目录

例如。

c:\some\location\
                \apples
                \oranges

to
c:\another\location\
                   \apples
                   \oranges

所以实际上我正在从source -> to -> target 重新创建所有文件夹。 不是递归的,顺便说一句。只是顶层。

所以到目前为止,我已经通过 PS:

dir -Directory | New-Item -ItemType Directory -Path (Join-Path "C:\jussy-test\" Select-Object Name)

dir -Directory | New-Item -ItemType Directory -Path "C:\new-target-location\" + Select-Object Name

我被困住了。我正在努力纠正最后一点。但无论如何,也许有人脑子里有更好的主意?

【问题讨论】:

  • 单行:dir -Path C:\some\location\* -Directory | % { New-Item -ItemType Directory -Path C:\another\location\ -Name $_.Name }

标签: powershell


【解决方案1】:

您的第一次尝试非常接近。您缺少的主要内容是如何迭代Get-Childitem(又名dir)的输出。为此,您需要通过管道发送至Foreach-Object

$srcDir = 'c:\some\location'
$destDir = 'c:\another\location'

dir $srcDir -Directory | foreach {
  mkdir (join-path $destDir $_.name) -WhatIf
}

foreach内部,变量$_保存当前对象,$_.Name选择Name属性。 (这也使用mkdir 代替New-Item -Directory,但它们大多可以互换)。

一旦您知道这段代码在做什么,删除-WhatIf 让它实际创建目录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-10
    • 2019-06-08
    相关资源
    最近更新 更多