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

PowerShell脚本开发:从CSV读取路径批量复制UNC文件至对应文件夹

解决PowerShell CSV对应文件复制问题

嘿,作为PowerShell新手能写出foreach循环已经很棒啦!其实要实现每个UNC路径文件对应复制到指定FolderName目录,核心就是在循环里把每一行的两个字段关联起来就行,我给你一步步拆解:

步骤1:读取CSV文件内容

首先用Import-Csv命令把CSV里的每一行数据转换成PowerShell能识别的对象,每个对象会自动包含FolderName和FilePath两个属性:

# 替换成你的CSV文件实际路径
$csvFilePath = "C:\example\yourdata.csv"
$fileMappings = Import-Csv -Path $csvFilePath

步骤2:遍历每一行并执行复制

在foreach循环里,针对每一行数据,直接调用Copy-Item把当前行的FilePath(UNC路径文件)复制到FolderName指定的目录。另外建议先检查目标目录是否存在,不存在就自动创建,避免复制失败:

foreach ($mapping in $fileMappings) {
    # 提取当前行的两个字段
    $sourceFile = $mapping.FilePath
    $targetFolder = $mapping.FolderName

    # 检查目标目录是否存在,不存在则创建
    if (-not (Test-Path -Path $targetFolder)) {
        New-Item -ItemType Directory -Path $targetFolder -Force | Out-Null
        Write-Host "已创建目标目录:$targetFolder"
    }

    # 执行文件复制,-Force参数可覆盖已存在的同名文件(按需选择)
    Copy-Item -Path $sourceFile -Destination $targetFolder -Force
    Write-Host "✅ 已完成复制:$sourceFile → $targetFolder"
}

完整脚本示例

把上面的代码整合起来,就是带错误处理的完整可用脚本:

# 配置CSV文件路径
$csvFilePath = "C:\example\yourdata.csv"

# 读取CSV数据
$fileMappings = Import-Csv -Path $csvFilePath

# 遍历执行复制
foreach ($mapping in $fileMappings) {
    $sourceFile = $mapping.FilePath
    $targetFolder = $mapping.FolderName

    # 创建目标目录(如果不存在)
    if (-not (Test-Path -Path $targetFolder)) {
        New-Item -ItemType Directory -Path $targetFolder -Force | Out-Null
        Write-Host "已创建目录:$targetFolder"
    }

    # 复制文件并捕获可能的错误
    try {
        Copy-Item -Path $sourceFile -Destination $targetFolder -Force
        Write-Host "成功复制:$sourceFile → $targetFolder"
    }
    catch {
        Write-Host "❌ 复制失败:$sourceFile`n错误信息:$_"
    }
}

几个实用提示

  • 确保你有UNC路径的读取权限和目标目录的写入权限,否则会出现权限报错
  • 检查CSV文件格式:第一行必须是FolderName,FilePath,后续行的内容不要有多余空格(如果路径本身包含逗号,需要用引号包裹路径)
  • 如果需要复制整个目录而非单个文件,给Copy-Item加上-Recurse参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:38:28