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

Sli*_*nky 3 windows powershell

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

Daily_Reviews[0001-0871].journal
Daily_Reviews[1002-9887].journal
[...]
Run Code Online (Sandbox Code Playgroud)

当我运行它时,方法"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
 }
Run Code Online (Sandbox Code Playgroud)

Sli*_*nky 5

好了,经过研究,我发现了一个解决方法:

$src = [Management.Automation.WildcardPattern]::Escape($sourcefile)
Copy-Item  $src $destination
Run Code Online (Sandbox Code Playgroud)


alr*_*roc 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
 }
Run Code Online (Sandbox Code Playgroud)

  • 方括号要求您在调用“copy-item”时使用“-literalpath”(我总是想知道何时需要它)。我修改了我的代码。 (2认同)