我正在尝试在某个目标位置创建目录(如果它们不存在)。
目录名称来自另一个源位置。
对于C:\some\location
中的每个目录名称
在 C:\another\location 中创建一个同名的新目录。
例如。
c:\some\location\
\apples
\oranges
to
c:\another\location\
\apples
\oranges
所以实际上我正在重新创建从源->到->目标
的所有文件夹。
顺便说一句,不是递归的。只是顶级。
到目前为止,我已经通过 PS 得到了这个:
dir -目录 | New-Item -ItemType Directory -Path(连接路径“C:\jussy-test\”选择对象名称)
或
dir -目录 | New-Item -ItemType Directory -Path "C:\new-target-location\"+ Select-Object Name
我被困住了。我正在努力把最后一点弄对。但无论如何,也许有人脑子里有更好的主意?
最佳答案
您已经非常接近第一次尝试了。您缺少的主要内容是如何迭代 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
以使其实际创建目录。
关于powershell - 尝试使用Powershell创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37403454/