2016-05-24 36 views
2

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

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

每个目录名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

,我被卡住。我试图让最后一点正确。但不管怎样,也许有人在脑海中有一个更好的主意?

+0

单行:'dir -Path C:\ some \ location \ * -Directory | %{New-Item -ItemType Directory -Path C:\ another \ location \ -Name $ _。Name}' – xXhRQ8sD2L7Z

回答

2

你非常接近你的第一次尝试。你缺少的主要是如何迭代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让它实际上创建目录。