复制包含文件夹名称的项目

问题描述

我需要一个 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

解决方法

当您将参数 -name 传递给 Get-ChildItem 时,它仅输出路径的文件名部分,例如。 G。 “file1.pdf”。这样 Copy-Item 没有关于文件文件夹的信息,将使用 working directory,无论在调用 Get-ChildItem 之前发生了什么。

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

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

作为进一步的优化,您可以将 -include 替换为 -filter,这样效率更高。来自docs

过滤器比其他参数更有效。提供者适用 当 cmdlet 获取对象而不是 PowerShell 时进行过滤 检索对象后对其进行过滤。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...