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

PowerShell Copy-Item报Illegal characters in path错误修复

问题根因

之前省略盘符再拼接前缀的方案报错,核心是路径解析逻辑和PowerShell文件系统提供程序的匹配规则冲突,和盘符冒号本身无关:

  • 列表中存储的\folder\file格式属于盘符根相对路径,PowerShell默认会将其解析为当前工作目录所在盘符的根路径,如果执行脚本时当前提示符不在C盘,拼接出的路径会直接错位。
  • 直接做字符串拼接"C:" + $relPath时,通配符、单文件路径中的特殊字符会被路径校验逻辑判定为非法字符:尤其是混用-Path和-LiteralPath参数时,*、?、[]这类通配符元字符如果没有被正确识别,会直接触发“Illegal characters in path”报错。
  • 目录场景能复制成功只是巧合:Copy-Item处理目录目标时会自动做路径规范化补全,绕过了单文件、通配符场景的严格路径校验,不是方案本身正确。
可落地修复方案

直接放弃“省略盘符存相对路径再拼接”的思路,路径列表里直接存储完整绝对路径,从根源避免解析异常,以下实现完全兼容完整目录、带通配符文件匹配、单文件三类路径,自动保留原始目录结构,路径列表直接内嵌在脚本中:

# 内嵌目标路径列表,直接写完整绝对路径即可,无需裁剪盘符
$targetList = @(
    "C:\test\full_dir",
    "C:\test\logs\*.log",
    "C:\test\config\settings.ini"
)
$destRoot = "D:\backup_target\" # 独立目标存储根路径

foreach ($path in $targetList) {
    # 识别路径是否包含通配符
    $hasWildcard = $path -match '[*?\[\]]'
    if ($hasWildcard) {
        # 通配符场景:匹配所有命中的文件
        $matchedItems = Get-ChildItem -Path $path -File -ErrorAction SilentlyContinue
        foreach ($item in $matchedItems) {
            # 计算相对路径,保留原始目录结构
            $relativePath = $item.FullName.Substring(2)
            $destPath = Join-Path $destRoot $relativePath.TrimStart('\')
            # 自动创建目标父目录
            $destDir = Split-Path $destPath -Parent
            if (-not (Test-Path $destDir)) {
                New-Item -ItemType Directory -Path $destDir -Force | Out-Null
            }
            Copy-Item -LiteralPath $item.FullName -Destination $destPath -Force
        }
    }
    else {
        if (-not (Test-Path -LiteralPath $path)) {
            Write-Host "路径不存在,跳过: $path"
            continue
        }
        $item = Get-Item -LiteralPath $path
        if ($item.PSIsContainer) {
            # 目录场景:递归复制保留结构
            $relativePath = $item.FullName.Substring(2)
            $destPath = Join-Path $destRoot $relativePath.TrimStart('\')
            Copy-Item -LiteralPath $item.FullName -Destination $destPath -Recurse -Force
        }
        else {
            # 单文件场景
            $relativePath = $item.FullName.Substring(2)
            $destPath = Join-Path $destRoot $relativePath.TrimStart('\')
            $destDir = Split-Path $destPath -Parent
            if (-not (Test-Path $destDir)) {
                New-Item -ItemType Directory -Path $destDir -Force | Out-Null
            }
            Copy-Item -LiteralPath $item.FullName -Destination $destPath -Force
        }
    }
}
排查验证要点
  • 所有路径拼接操作统一用Join-Path,不要直接做字符串拼接,该cmdlet会自动处理斜杠转义、特殊字符兼容问题,避免出现双斜杠、字符转义错误。
  • 触发非法字符报错时,优先输出拼接完成的全路径做校验,90%以上的报错来自拼接后路径错位、通配符被错误转义、存在不可见特殊字符。
  • 只要路径中包含[]这类PowerShell通配符元字符,必须用-LiteralPath参数传参,否则PowerShell会将方括号内容识别为字符范围匹配规则,直接触发路径校验错误。

注:如果需要跨盘符复制,只需要修改路径列表中的盘符前缀和目标根路径即可,逻辑不需要做额外调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 10:36:25