Search code examples
powershellpowershell-2.0copy-item

copy-item a file with strange characters in filename (i.e [])


I must copy a file names as follow

  $filename = "Sport.EL#15.csv.[]"

into another folder.

if I use

  copy-item -force Sport.EL#15.csv.[] $dest_path 

it doesn't work.

since I do that:

  foreach ($f in Get-ChildItem $pathfile | Where {!$_.PsIsContainer} | Where {$_.Name -match $filename}){....}

and the error is

  Bad argument to operator '-match': parsing "Sport.EL#15.csv.[]" - Unterminated [] set..

I think the problem is the [] in the filename. how can I workaround?


Solution

  • try use:

    copy-item -literalpath $filename $dest_path 
    

    Edit after comment:

    to resolve the -match issue try:

     Where {$_.Name -match [regex]::escape($filename)}
    

    -match take a regular expression value and you need to escape each special character used in regex language to avoid problems like this.