如何导入CSV提取指定分隔符前数据,匹配并重命名四级深度文件夹
修正后的PowerShell脚本(按分隔符提取+指定深度文件夹重命名)
问题解决要点
替换原脚本中硬编码的10字符匹配逻辑,改为按**空格-空格(-)**分隔符提取Column3前缀,同时精准定位四级深度文件夹,用Column1中-后的6位字符完成重命名。
完整脚本
# 配置参数(根据实际情况修改) $csvPath = "C:\your\path\data.csv" $rootSearchPath = "\\fileserver\your\root\directory" # 搜索起始根路径 $targetDepth = 4 # 要匹配的文件夹深度(相对于根路径的层级,从1开始计数) # 导入CSV数据 $csvData = Import-Csv -Path $csvPath foreach ($row in $csvData) { # 提取Column3中“ - ”之前的内容(兼容任意长度、含空格的情况) $searchKeyword = $row.Column3 -split ' - ', 2 | Select-Object -First 1 if ([string]::IsNullOrWhiteSpace($searchKeyword)) { Write-Warning "Column3格式无效,跳过行:`n$($row | Out-String)" continue } # 提取Column1中“-”后的6位字符(添加格式校验) $newFolderName = $row.Column1 -split '-', 2 | Select-Object -Skip 1 -First 1 if ([string]::IsNullOrWhiteSpace($newFolderName) -or $newFolderName.Length -ne 6) { Write-Warning "Column1不符合要求(需包含'-'后6位字符),跳过行:`n$($row | Out-String)" continue } # 筛选指定深度且名称包含关键词的文件夹 $targetFolders = Get-ChildItem -Path $rootSearchPath -Directory -Recurse -Depth ($targetDepth - 1) | Where-Object { # 计算当前文件夹相对于根路径的层级 $relativePath = $_.FullName.Substring($rootSearchPath.Length).TrimStart('\') $folderDepth = ($relativePath -split '\\').Count # 匹配深度+名称关键词 $folderDepth -eq $targetDepth -and $_.Name -like "*$searchKeyword*" } # 处理匹配结果 switch ($targetFolders.Count) { 0 { Write-Warning "未找到包含关键词「$searchKeyword」的四级深度文件夹,跳过行:`n$($row | Out-String)" continue } { $_ -gt 1 } { Write-Warning "找到多个匹配「$searchKeyword」的文件夹,跳过行:`n$($row | Out-String)" continue } default { # 执行重命名(添加异常捕获) try { Rename-Item -Path $targetFolders.FullName -NewName $newFolderName -ErrorAction Stop Write-Host "✅ 成功重命名: $($targetFolders.Name) → $newFolderName" } catch { Write-Error "❌ 重命名失败: $_" } } } }
关键逻辑说明
Column3关键词提取:
用-split ' - ', 2实现按指定分隔符拆分,2限制仅拆分一次(避免内容中存在多个-的情况),确保准确获取分隔符前的完整内容,兼容任意长度、含空格的场景。四级深度文件夹定位:
通过计算文件夹的相对路径层级数,精准匹配四级深度的文件夹,避免误操作其他层级的目录。-Depth ($targetDepth - 1)用于限制递归范围,提升搜索效率。格式校验与异常处理:
- 校验Column1提取的新名称是否为6位字符,避免无效命名
- 处理无匹配、多匹配的情况,输出明确警告
- 用
try-catch捕获重命名时的权限冲突、文件夹已存在等异常
示例验证
假设CSV数据:
Column1,Column3 INV-123456,Project Alpha - Q3 2024 INV-789012,Client XYZ Corp - Onboarding INV-345678,9CharTest - Demo
匹配到的四级深度文件夹:
\\fileserver\root\DeptA\Projects\2024Q3\Project Alpha Docs\\fileserver\root\DeptB\Clients\New\Client XYZ Corp Files\\fileserver\root\DeptC\Tests\Demo\9CharTest Folder
执行脚本后,文件夹将被重命名为:
123456789012345678
内容的提问来源于stack exchange,提问作者Nowhere Atoll
相关产品推荐
相关产品推荐

