在多个特定父文件夹的子文件夹创建
问题描述:
我们当前的文件夹结构\服务器的\ usr \所有客户端\与每一个客户(咨询,财务,工资,永久的,税务)在多个文件夹中当前\ CLIENT_NAME。在多个特定父文件夹的子文件夹创建
我需要创建子文件夹,在短短的财务,工资和税收称为2017年和2018年。
有超过2000的客户,所以我想使用PowerShell脚本来做到这一点。我找到了以下示例,但它在财务下的所有文件夹中创建了2017子文件夹。
foreach ($folder in (Get-ChildItem '\\server\Usr\All Clients\Current\*\Financials' -Directory))
{
new-item -ItemType directory -Path ($folder.fullname+"\2017")
}
我如何才能在特定文件夹中创建2017?
答
您将需要一个地方对象来选择要在
# Get folders that are Financials, Payrol, or Tax
$Folders = Get-ChildItem '\\server\Usr\All Clients\Current\*' | Where-Object -Property Name -in -Value 'Financials','Payroll','Tax'
# Loop through those folders
foreach ($Folder in $Folders)
{
$2017Path = Join-Path -Path $Folder.FullName -ChildPath '2017' # Generate path to 2017 folder
$2018Path = Join-Path -Path $Folder.FullName -ChildPath '2018' # Generate path to 2018 folder
New-Item -Path $2017Path -Force # Create 2017 folder
New-Item -Path $2018Path -Force # Create 2018 folder
}
创建文件夹使用New-Item -WhatIf
的文件夹,如果你想看到正在创建的文件夹,其中的输出。我无法完全测试,因为我无法访问您的特定环境。
答
试试这个。这是未经测试,但如果它不工作100%,这将让你非常接近。
#requires -Version 5
$createFolders = '2017','2018'
@(Get-ChildItem -Path '\\server\Usr\All Clients\Current' -Recurse -Directory -Depth 1).where({ $_.Name -in 'financials','payroll','tax' }).foreach({
$clientFolder = $_.FullName;
$createFolders | foreach {
$null = mkdir -Path "$clientFolder\$_"
}
})
答
你可以使用一个数组来存储的目录在其中创建2017年和2018年
$ParentDirectories = @("Financials", "Payroll", "Tax")
然后,过滤与阵列创建子目录的文件夹。
Get-ChildItem -Path '\server\Usr\All Clients\Current\' | ForEach-Object {
$Client = $_.Name;
Get-ChildItem -Path $Client | Where-Object { $_.Name -in $ParentDirectories } | ForEach-Object {
New-Item -ItemType Directory @("$Client\$_\2017", "$Client\$_\2018")
}
}
希望它有帮助!
编辑:测试和工程!
答
为什么不直接堆放一些的ForEach:
ForEach ($Client in (Get-ChildItem "\\server\Usr\All Clients\Current\*" -Directory)){
ForEach ($Depth in 'Financials','Payroll','Tax') {
ForEach ($Year in '2017','2018') {
New-Item -ItemType Directory -Path ("{0}\{1}\{2}" -f $($Client.fullname),$Depth,$Year) -Whatif
}
}
}
如果输出看起来不错,除去-WhatIf
Sample run on my Ramdrive A: with pseudo clients Baker,Miller,Smith:
> tree
A:.
├───Baker
│ ├───Financials
│ │ ├───2017
│ │ └───2018
│ ├───Payroll
│ │ ├───2017
│ │ └───2018
│ └───Tax
│ ├───2017
│ └───2018
├───Miller
│ ├───Financials
...
└───Smith
├───Financials
│ ├───2017
│ └───2018
├───Payroll
│ ├───2017
│ └───2018
└───Tax
├───2017
└───2018
奏效!感谢Adam – e1mariem
太棒了!你能将它标记为已回答吗?不知道当我帮助解决你的问题时我为什么会低调,但是哦。 :) –