PowerShell 复制项目方法失败 - 文件名中的方括号 [英] PowerShell Copy-Item Method Fails - Brackets in Filename

查看:40
本文介绍了PowerShell 复制项目方法失败 - 文件名中的方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 PowerShell (v.1) 仅复制与模式匹配的文件.文件命名约定是:

I am trying to use PowerShell (v.1) to copy over only files that match a pattern. The file naming convention is:

Daily_Reviews[0001-0871].journal
Daily_Reviews[1002-9887].journal
[...]

当我运行它时,方法Copy-Item"抱怨:

When I run it, the method "Copy-Item" complains:

无法检索 cmdlet 的动态参数.指定的通配符模式无效:Daily_Reviews[0001-0871].journal
+复制项目<<<<<$sourcefile $destination

错误是由文件名中的["和]"引起的.当我删除左右括号时,它按预期工作.但看起来 PowerShell 1 没有 -LiteralPath 标志,那么还有另一种方法可以让 Copy-Item 在 PowerShell 1 中使用包含括号的文件名吗?

The error is due to the "[" and "]" in the file names. When I remove the left and right brackets, it works as expected. But looks like PowerShell 1 doesn't have the -LiteralPath flag so is there another way to get Copy-Item to work in PowerShell 1 with file names that contain brackets?

$source = "C:\Users\Tom\"
$destination ="C:\Users\Tom\Processed\"

if(-not(Test-Path $destination)){mkdir $destination | out-null}


ForEach ($sourcefile In $(Get-ChildItem $source | Where-Object { $_.Name -match "Daily_Reviews\[\d\d\d\d-\d\d\d\d\].journal" }))
{

  Copy-Item $sourcefile $destination
 }

推荐答案

好吧,经过深入研究后,我找到了一个解决方法:

Well, after researching this more I found a workaround:

$src = [Management.Automation.WildcardPattern]::Escape($sourcefile)
Copy-Item  $src $destination

这篇关于PowerShell 复制项目方法失败 - 文件名中的方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆