powershell - 尝试使用Powershell创建目录

标签 powershell

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

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

对于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/

相关文章:

powershell - Powershell从每一行读取一些字符串

powershell - Get-WMIObject 返回一个没有描述的错误

powershell - 获取SqlInstance : The operation failed on target server

powershell - 为什么安全字符串需要force和AsPlainText

windows - 在 Windows 10 命令行中启用 git

windows - 为什么 PowerShell 无法正确显示 "DarkYellow"文本?

xml - 将新的子项追加到特定节点

powershell - 在 PowerShell 中使用 NLog ${callsite} 和 ${callsite-linenumber}

Powershell 电子邮件 : How to add new line in email Body?

python - 创建 Windows 10 桌面快捷方式以在 venv 虚拟环境中运行 python 脚本