PowerShell Copy-Item Method Fails - Brackets in Filename

女生的网名这么多〃 提交于 2021-02-04 18:26:27

问题


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
[...]

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

Dynamic parameters for cmdlet cannot be retrieved. The specified wildcard pattern is not valid: Daily_Reviews[0001-0871].journal
+ Copy-Item <<<< $sourcefile $destination

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
 }

回答1:


Well, after researching this more I found a workaround:

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



回答2:


$_ references the currently-referenced argument; you can't use it the way that you are here because that's outside the pipeline.

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


来源:https://stackoverflow.com/questions/15929985/powershell-copy-item-method-fails-brackets-in-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!