在多个目录中创建相同文件夹的PowerShell脚本

时间:2018-11-09 13:18:30

标签: windows powershell windows-10

当前文件夹结构:

\\Server\Source\A1\A1 101\
\\Server\Source\A1\A1 102\

\\Server\Source\A2\A2 101\
\\Server\Source\A2\A2 102\

\\Server\Source\A3\A3 101\
\\Server\Source\A3\A3 102\

我需要能够在源(A1 101,A2 101等)下的每个第二级文件夹内创建3个文件夹A,B和C。 FolderDir.txt在自己的行上有A,B,C。除了以下以外,还有更好的方法吗?子目录比上面列出的要多:

Foreach($folder in Get-Content "C:\temp\folderDir.txt")
{
    New-Item "\\Server\Source\A1\A1 101\$folder" -ItemType directory
    New-Item "\\Server\Source\A1\A1 102\$folder" -ItemType directory
    New-Item "\\Server\Source\A2\A2 101\$folder" -ItemType directory
    New-Item "\\Server\Source\A2\A2 102\$folder" -ItemType directory
    New-Item "\\Server\Source\A3\A3 101\$folder" -ItemType directory
    New-Item "\\Server\Source\A3\A3 102\$folder" -ItemType directory
}

谢谢!我对PowerShell还是很陌生。

这是我想出的:

Foreach($folder in Get-Content "C:\temp\folderDir.txt")
{
$lesson = Get-ChildItem -Path \\Server\Source\A*\*
New-Item $lesson\$folder -ItemType Directory
}

但是我得到了错误:

New-Item : Could not find a part of the path 'A'.
At line:4 char:1
+ New-Item $lesson\$folder -ItemType Directory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\Server\Source...\A:String) [New-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : CreateDirectoryIOError,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : Could not find a part of the path 'B'.
At line:4 char:1
+ New-Item $lesson\$folder -ItemType Directory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\Server\Source...\B:String) [New-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : CreateDirectoryIOError,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : Could not find a part of the path 'C'.
At line:4 char:1
+ New-Item $lesson\$folder -ItemType Directory
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (\\Server\Source...\C:String) [New-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : CreateDirectoryIOError,Microsoft.PowerShell.Commands.NewItemCommand

但是,如果在末尾(“目录”之后)放置-WhatIf命令,它似乎可以执行我想要的操作...

1 个答案:

答案 0 :(得分:0)

由于文件夹列表已多次迭代,因此应首先读取

未测试:

$folderlist = Get-Content "C:\temp\folderDir.txt"
Get-ChildItem -Path '\\Server\Source\*\*' -Directory | ForEach-Object {
  ForEach ($folder in $folderlist){
    New-Item (Join-Path $_.FullName $folder) -ItemType directory -Force -WhatIf
  }
}

如果输出看起来正常,请删除-WhatIf