PowerShell复制TXT清单文件:如何保留重名文件并过滤无效行
解决PowerShell复制文件时的无效行报错与重名覆盖问题
我来帮你搞定这两个痛点!咱们一步步来解决:
第一步:过滤无效的InputStream行
原来生成的test.txt里混进了无效的InputStream条目,咱们先把它过滤掉。可以直接修改生成路径清单的命令,确保输出只有有效的文件路径:
Get-ChildItem -Recurse | Select-String -Pattern "acrn164524" | Group-Object Path | Select-Object -ExpandProperty Name | Where-Object { $_ -ne 'InputStream' } > test.txt
这里用Where-Object把等于InputStream的行直接排除,这样test.txt里就全是靠谱的文件路径了。
第二步:重名文件自动追加编号保留
接下来解决重名覆盖的问题,咱们不能直接用-Force硬覆盖,而是要检查目标路径是否存在,自动生成带编号的文件名(比如file.txt→file(1).txt→file(2).txt):
Get-Content "test.txt" | ForEach-Object { # 定义源路径和目标目录 $sourcePath = $_ $destinationDir = "c:\destination\" # 获取源文件名,拼接初始目标路径 $fileName = [System.IO.Path]::GetFileName($sourcePath) $destPath = Join-Path -Path $destinationDir -ChildPath $fileName $counter = 1 # 循环检查目标路径是否存在,直到找到可用的新路径 while (Test-Path -Path $destPath) { $fileBaseName = [System.IO.Path]::GetFileNameWithoutExtension($sourcePath) $fileExtension = [System.IO.Path]::GetExtension($sourcePath) $destPath = Join-Path -Path $destinationDir -ChildPath "$fileBaseName($counter)$fileExtension" $counter++ } # 执行复制操作 Copy-Item -Path $sourcePath -Destination $destPath -Recurse -Container -Force }
更高效的合并版(无需中间文件)
如果你不想生成test.txt中间文件,可以直接把两步合并成一个命令,一气呵成:
Get-ChildItem -Recurse | Select-String -Pattern "acrn164524" | Group-Object Path | Select-Object -ExpandProperty Name | Where-Object { $_ -ne 'InputStream' } | ForEach-Object { $sourcePath = $_ $destinationDir = "c:\destination\" $fileName = [System.IO.Path]::GetFileName($sourcePath) $destPath = Join-Path -Path $destinationDir -ChildPath $fileName $counter = 1 while (Test-Path -Path $destPath) { $fileBaseName = [System.IO.Path]::GetFileNameWithoutExtension($sourcePath) $fileExtension = [System.IO.Path]::GetExtension($sourcePath) $destPath = Join-Path -Path $destinationDir -ChildPath "$fileBaseName($counter)$fileExtension" $counter++ } Copy-Item -Path $sourcePath -Destination $destPath -Recurse -Container -Force }
这样运行后,不仅不会因为无效行报错,所有重名文件也会自动带上编号保留下来,不会被覆盖~
内容的提问来源于stack exchange,提问作者JJD
相关产品推荐
相关产品推荐

