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

PowerShell脚本无法复制并重命名PDF文件问题求助

PowerShell 文件复制未生效问题解决

场景说明:读取C:\temp目录下的XML文件,提取两个目标内容:

  • $rg:10位数字(如0123456789)
  • $file:PDF文件名(如1.pdf)
    需求是将原PDF文件复制到C:\temp\output子目录,并重命名为[10位数字].pdf,但原脚本执行无报错却未完成复制操作。

原脚本问题分析

原脚本中,$rg和$file的提取逻辑存在核心问题:

$rg = Get-Content -Path $name | Select-String -Pattern "(?<=\#\s)(\d{10})" | Select-Object {$_.matches.groups[0].Value} | select -first 1
$file = Get-Content -Path $name | Select-String -Pattern "[0-9].pdf" | Select-Object {$_.matches.groups[0].Value} | select -first 1  

通过Select-Object {$_.matches.groups[0].Value}得到的是自定义对象,而非纯字符串值。直接在Copy-Item的路径中引用$file或$rg时,PowerShell会将对象转为类型描述字符串(类似@{ $_.matches.groups[0].Value=0123456789 }),导致实际路径无效——因为不存在对应文件名的文件,所以Copy-Item无报错但实际未执行复制。

修正方案

优化后的完整脚本

先正确提取纯字符串值,再执行复制操作,代码更简洁易维护:

$inputfile = Get-ChildItem -Path C:\temp\*.xml
# 确保输出目录存在,不存在则创建
New-Item -Path "C:\temp\output" -ItemType Directory -Force | Out-Null

foreach ($name in $inputfile)
{
    # 提取10位数字并转为字符串
    $rgMatch = Get-Content -Path $name | Select-String -Pattern "(?<=\#\s)(\d{10})" | Select-Object -First 1
    $rg = $rgMatch.Matches.Groups[0].Value

    # 提取PDF文件名并转为字符串
    $fileMatch = Get-Content -Path $name | Select-String -Pattern "[0-9].pdf" | Select-Object -First 1
    $file = $fileMatch.Matches.Groups[0].Value

    # 执行复制并重命名
    Copy-Item -Path "C:\temp\$file" -Destination "C:\temp\output\$rg.pdf"
}

关于你修改后的命令说明

你修改后的Copy-Item命令通过$($rg.'$_.matches.groups[0].Value')的方式,强制访问了自定义对象的属性(属性名是脚本块的字符串),同时用New-Item预先创建文件路径,确实能生效,但逻辑较为冗余。上面的优化方案直接提取纯字符串值,避免了对象转字符串的异常问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 08:07:29