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

PowerShell脚本路径创建错误:未正确保留子文件夹结构

PowerShell脚本子文件夹路径重复问题

问题描述

脚本预期将处理后的文件生成在Txt_ENG文件夹内并保留原有子文件夹结构,但实际生成路径出现重复。例如:

  • 当前工作目录:G:\Games\Files here
  • 源文件路径:G:\Games\Files here\current\csv\abc.csv
  • 预期输出路径:G:\Games\Files here\Txt_ENG\current\csv\abc.txt
  • 实际输出路径:G:\Games\Files here\Txt_ENG\Games\Files here\current\csv\abc.txt

问题原因

核心问题出在相对路径计算部分:

$relativePath = $csvFile.FullName.Substring($SourceDir.Length + 1)

$SourceDir默认值是$PWD,而$PWD返回的是FileSystemInfo对象,不是纯字符串路径。直接取$SourceDir.Length时,获取的是对象的属性长度(而非路径字符串的长度),导致Substring截取位置错误,最终拿到的不是相对路径,而是包含完整盘符后的路径片段,拼接后就出现了路径重复。

修正方案

推荐使用系统API直接获取相对路径,避免手动截取的错误:

修正后的完整脚本

param(
  $FileName = '*.csv', # 文件名称过滤器
  $SourceDir = $PWD,   # 输入文件目录
  $OutDir = $PWD,      # 输出文件目录
  $ColumnIndex = 3,    # 目标列的1-based索引
  $OutFileBaseNameSuffix = "_column$ColumnIndex"
)

# 定义目标文件夹
$destinationFolder = Join-Path -Path $OutDir -ChildPath "Txt_ENG"

# 若目标文件夹不存在则创建
if (-not (Test-Path -Path $destinationFolder)) {
    New-Item -Path $destinationFolder -ItemType Directory | Out-Null
}

foreach ($csvFile in Get-ChildItem -LiteralPath $SourceDir -Recurse -Filter $FileName -File) {

  # 导入当前文件的所有行
  $rows = Import-Csv $csvFile.FullName
  # 根据指定索引确定目标列名称(数组索引从0开始,所以减1)
  $colName = ($rows[0].psobject.Properties.Name)[$ColumnIndex-1]

  # 构造目标路径,保留子文件夹结构(使用系统API获取可靠相对路径)
  $relativePath = [System.IO.Path]::GetRelativePath($SourceDir, $csvFile.FullName)
  $destinationPath = Join-Path -Path $destinationFolder -ChildPath $relativePath

  # 若目标目录不存在则创建
  $destinationDirectory = Split-Path -Path $destinationPath -Parent
  if (-not (Test-Path -Path $destinationDirectory)) {
      New-Item -Path $destinationDirectory -ItemType Directory | Out-Null
  }

  # 确定输出文件路径和名称
  $outFile = Join-Path $destinationDirectory ('{0}.txt' -f $csvFile.BaseName)

  # 以无BOM的UTF-8格式写入文件
  $null =
  Set-Content -Path $outFile -Value (
    $colName + "`n" + ($rows.$colName -join "`n") + "`n"
  ) -Encoding UTF8
}

关键改动说明

  • 替换了相对路径的计算方式,使用[System.IO.Path]::GetRelativePath()确保正确获取源文件相对于$SourceDir的路径
  • 避免了手动字符串截取可能带来的长度计算错误,处理包含空格或特殊字符的路径时更可靠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:33:23