You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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-Object block 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 $num variable 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 Extension property, so $_.Extension would always be empty, breaking your renaming logic

Script Version 2

  • Stale Folder Inventory: $destFolders was only loaded once at the start, so it didn't account for pre-existing numbered folders in the target directory (like john(1) if it was already there)
  • Broken Error Logging: In the catch block, $_.FullName refers 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 $newName instead 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-Path directly 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 $newFolderName is generated (e.g., use underscores instead of parentheses)
  • Unique CSV Entries: Uses -Unique on the CSV folder names to avoid processing the same folder multiple times

内容的提问来源于stack exchange,提问作者yaniv naor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:23:01