5

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
 }

2 Answers 2

7

Well, after researching this more I found a workaround:

$src = [Management.Automation.WildcardPattern]::Escape($sourcefile)
Copy-Item  $src $destination
Sign up to request clarification or add additional context in comments.

1 Comment

If the brackets are in the directory name, better use this : $src = [Management.Automation.WildcardPattern]::Escape($sourcefile.FullName)
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
 }

4 Comments

Thanks. I made the change that you suggested and I get the same exact complaints from Copy-Item...Weird stuff. I wonder if it's the brackets in the filenames? –
It's because of the "[" and "]" in the file names. When I remove the left and right brackets, it works as expected. Needs to be able to parse files with brackets though
The square brackets require that you use -literalpath (always wondered when I'd need that) when calling copy-item. I've amended my code.
@alroc Without -LiteralPath globbing takes place, so you need the option when a literal file or folder name contains wildcard characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.