基于CSV列表移动文件夹并对重名项编号重命名的PowerShell脚本求助
Let's walk through fixing your scripts and get this folder-moving task working properly. First, let's break down what was wrong with each version, then share a fully functional script that meets your requirements.
Issues in Your Original Scripts
Script Version 1
- Critical Syntax Errors: The
ForEach-Objectblock wasn't properly closed, so all the code after the initial pipeline was running outside the loop scope (this is why it failed entirely) - Invalid Path Check:
Test-Path (Get-ChildItem -Path $src -Recurse | select name)is nonsensical—it's trying to check if a collection of folder names is a valid path, which it never will be - Unreset Counter: The
$numvariable didn't reset for each folder, so you'd end up with sequential numbering across all folders (e.g.,folder1_1,folder2_2) instead of starting at 1 per duplicate set - Misused Folder Properties: Folders don't have an
Extensionproperty, so$_.Extensionwould always be empty, breaking your renaming logic
Script Version 2
- Stale Folder Inventory:
$destFolderswas only loaded once at the start, so it didn't account for pre-existing numbered folders in the target directory (likejohn(1)if it was already there) - Broken Error Logging: In the catch block,
$_.FullNamerefers to the error record object, not the folder you were trying to move—so your error log would have incorrect paths - Ineffective Duplicate Check: Using
$destFolders -contains $newNameinstead of checking the actual filesystem meant you could accidentally try to create a folder that already exists
Working Solution
This script fixes all the above issues, handles duplicate folder names correctly, and includes proper error logging:
$src = "C:\Users\Yaniv Naor\Desktop\users" $dest = "C:\Users\Yaniv Naor\Desktop\oldusers" $CsvFile = "C:\Users\Yaniv Naor\Desktop\Disable_users.csv" $errorLog = Join-Path -Path $dest -ChildPath ('{0:yyyy-MM-dd}_Errors.txt' -f (Get-Date)) # Get unique folder names from your CSV (confirm the column name is "users"!) $targetFolderNames = Import-Csv $CsvFile | Select-Object -ExpandProperty users -Unique # Process each matching folder in the source directory Get-ChildItem -Path $src -Directory | Where-Object { $targetFolderNames -contains $_.Name } | ForEach-Object { $currentFolder = $_ $baseFolderName = $currentFolder.Name $newFolderName = $baseFolderName $counter = 1 # Keep generating new names until we find one that doesn't exist in the target while (Test-Path -Path (Join-Path $dest $newFolderName)) { # Customize the naming format here if you prefer (e.g., "$baseFolderName_$counter" instead of parentheses) $newFolderName = "$baseFolderName($counter)" $counter++ } $finalDestination = Join-Path $dest $newFolderName try { # Move the folder with strict error handling Move-Item -Path $currentFolder.FullName -Destination $finalDestination -Force -ErrorAction Stop Write-Host "Successfully moved '$($currentFolder.Name)' to '$finalDestination'" } catch { $errorDetails = "Failed to move '$($currentFolder.Name)': $($_.Exception.Message)" Write-Warning $errorDetails # Log the error with a timestamp for debugging Add-Content -Path $errorLog -Value "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $errorDetails" } }
Key Improvements
- Real-Time Duplicate Check: Uses
Test-Pathdirectly on the target filesystem to verify if a folder name exists, so it catches pre-existing numbered folders - Per-Folder Counter Reset: The counter starts at 1 for every folder, so duplicates of different folders don't share a sequential number
- Accurate Error Logging: Stores the current folder in a variable (
$currentFolder) so we can reference its details correctly in the catch block - Flexible Naming: You can easily switch the duplicate naming format by modifying the line where
$newFolderNameis generated (e.g., use underscores instead of parentheses) - Unique CSV Entries: Uses
-Uniqueon the CSV folder names to avoid processing the same folder multiple times
内容的提问来源于stack exchange,提问作者yaniv naor
相关产品推荐
相关产品推荐

