【问题标题】:PowerShell script to check the names of all directories and create subfolders in each onePowerShell 脚本检查所有目录的名称并在每个目录中创建子文件夹
【发布时间】:2021-08-08 18:05:40
【问题描述】:

我有一个主文件夹,其中包含许多名称格式为:大写字母和四个数字 (A4431) 的文件夹。我正在尝试编写的 Powershell 中的脚本需要遍历我的主文件夹中的所有文件夹并检查它们是否具有正确的名称格式,如果不正确则更改它。之后它需要在我的主文件夹中的每个文件夹中创建一个子文件夹结构。子文件夹结构由 4 个文件夹组成,其中一个有自己的子文件夹。子文件夹结构的名称始终相同。最终结果应如下所示:

Main Folder
 **-A4431**
  -Customers
  -Supplier
  -Orders
    -Sub Folder1
    -Sub Folder2
  -Items
 **-C1131**
  -Customers
  -Supplier
  -Orders
    -Sub Folder1
    -Sub Folder2
  -Items
...

我是 Powershell 的初学者,所以我想出的解决方案一团糟,但我还是发布了它。

$root = "C:\Work files\Test\Main folder"

#Folder name example (A3234)
$pattern = "^([a-zA-Z]){1}\d{4}"

#Subfolder structure needed to be created in each folder
$folders_names = "Customers","Supplier","Orders","Items"

#Get all folders in $root
$dirs = Get-ChildItem $root | Where-Object {$_.Attributes -eq "Directory"}

#loop through all folders in root and check if they have the right name format and change it if necessary
ForEach ($dir in $dirs)
{
    if(!$dir -match $pattern){
        $newName = '{0}{1}' -f ($_.BaseName -replace '([a-zA-Z]){1}\d{4}') 
        $_ | Rename-Item -NewName $newName -Force 
    }
    #create subfolders in each folder in $root
    ForEach ($name in $folder_names){
        New-item -path "$root\$dir" -Name $name -Type 'directory'
    }
}

【问题讨论】:

  • 欢迎来到 SO。请说明您对代码的问题。我自己对 Powershell 了解不多,但您的模式应该是 ([A-Z])\d{4}(不需要 {1},只有 A-Z,因为您需要一个大写字母/我不知道您需要哪些组)。也许regex101.com 可以提供帮助。
  • 嗨@AndyA。我添加了非大写字母,因为我也认为它是正确的。主要问题是如何首先根据模式检查文件夹名称,然后更改它们的名称,所以它是正确的。第二个大问题是如何在每个文件夹中创建子文件夹结构。到目前为止,我还没有弄清楚如何使用自己的子文件夹创建子文件夹。我发布的代码似乎根本不起作用。
  • $_ 只能在管道内工作(例如$dirs | foreach-object { $_ ... etc ... })。你的意思可能是$dir 在你的foreach( $dir in $dirs )
  • pattern 不匹配时父文件夹的重命名条件非常不清楚。您应该提供更多详细信息。
  • 如果名称格式正确,请详细说明",如果不正确,请更改"。如果一个文件夹被称为 'imphetuss_stuff'.. 将其重命名为 ????那里的策略是什么?

标签: regex powershell rename


【解决方案1】:

这应该可以帮助您入门。它没有解决第一级目录的命名或第三级目录的添加,但您应该看到有关如何完成此操作的逻辑。提示:$NewDir 将包含创建目录的路径!

$Root = "C:\Work files\Test\Main folder"

[Array]$Dirs = Get-ChildItem -LiteralPath $Root -Directory -Depth 0

$NewFolds = @("Customers","Supplier","Orders","Items")

ForEach ($Dir in $Dirs) {

  $NIArgs = @{Path     = "$Root\$Dir"
              ItemType = "Directory"}

  For ($Cntr = 0; $Cntr -lt $NewFolds.Count; $Cntr++) {
    $NewDir = New-Item @NIArgs -Name $($NewFolds[$($Cntr)])
  } #End For ($Cntr...

} #End ForEach ($Dir..

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多