windows - 复制包含文件夹名称的项目
问题描述
我需要一个 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
,它仅输出路径的文件名部分,例如“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 在检索到对象后对其进行筛选。
推荐阅读
- json - 如何在 TypeScript Angular 8 中动态地将普通字符串转换为 JSON 数组
- javascript - Vue:导入特定组件时,我收到类型错误
- react-native - AdMobInterstitial React Native
- c++ - 为什么它在运行时显示 sigsegv 错误?
- reactjs - 是否需要使用 react-share 导入元标签
- php - 为什么 For 可以工作,而 ForEach 在 PHP 中却不行?
- properties - 如何在 Rhapsody 中创建只读属性
- angular - 带有 SPA 角度应用程序的 Azure APIM API 安全性
- ms-access - MS Access 2010:网络位置上无法识别的数据库格式
- javascript - 单击 EN 更改为 AR,反之亦然