首页 > 解决方案 > 复制包含文件夹名称的项目

问题描述

我需要一个 Windows 脚本来复制一些文件,这些文件包含对文件夹的引用,该文件夹的名称中包含引用的名称。

示例:文件K:\examplefolder\sourcefolder\example3456file.pdf转到文件夹K:\examplefolder\Destfolder\3456.

我创建了这个:

$Src =  'K:\Escritorio\Scripts\Script_copiar_planos\Script OT\Origen'
$Dst = 'K:\Escritorio\Scripts\Script_copiar_planos\Script OT\Destino'
$file = 'K:\Escritorio\Scripts\Script_copiar_planos\Script OT\referencias.txt'

foreach ($referencia in Get-Content $file){
  Get-ChildItem  -Path $Src -Recurse -include *$referencia*.pdf -name -file | Copy-item -Destination $Dst\$referencia 
}

referencias.txt参考文献中列出如下:

5678
91011
121314

对我来说显然没问题,但是当我执行脚本时,它会删除以下错误:

Copy-item : No se encuentra la ruta de acceso 'K:\Escritorio\Scripts\PDF-Con-81006600-en-el-nombre - copia (2).pdf' porque no existe.
En K:\Escritorio\Scripts\Script_copiar_planos\mover.ps1: 11 Carácter: 81
+ ... referencia*.pdf -name -file | Copy-item -Destination $Dst\$referencia
+                                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (K:\Escritorio\S...- copia (2).pdf:String) [Copy-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand

标签: windowspowershellscriptingget-childitemcopy-item

解决方案


当您将参数传递-name给 时Get-ChildItem,它仅输出路径的文件名部分,例如“file1.pdf”。这种方式Copy-Item没有关于文件文件夹的信息,并且将使用工作目录,无论在调用Get-ChildItem.

删除参数-name以将完整的源路径传递给Copy-Item

Get-ChildItem  -Path $Src -Recurse -include *$referencia*.pdf -file | Copy-item -Destination $Dst\$referencia 

作为进一步的优化,您可以替换-include-filter,这样更有效。从文档

过滤器比其他参数更有效。提供程序在 cmdlet 获取对象时应用筛选器,而不是让 PowerShell 在检索到对象后对其进行筛选。


推荐阅读