PowerShell复制项方法失败 - 文件名中的括号

时间:2013-04-10 15:21:45

标签: windows powershell

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

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

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

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

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

$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
 }

2 个答案:

答案 0 :(得分:5)

嗯,在研究了这个之后我发现了一个解决方法:

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

答案 1 :(得分:2)

$_引用当前引用的参数;你不能像你在这里那样使用它,因为那是在管道之外。

$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 -literalpath $sourcefile $destination
 }