1

i use this code to add a text to some files:

gci C:\Users\Documents\SAMPLE\* -in *.mp4,*.mkv -Recurse | % { rename-item –path $_.Fullname –Newname ( $_.basename +  ' (TEST)' + $_.extension) }

it works as i want BUT it does not work with files that their name contaion "[ ]" and give me this error:

Cannot rename because item at 'C:\Users\Documents\SAMPLE\AAAAAAAAA[B].mp4' does not exist.

Compo
  • 36,585
  • 5
  • 27
  • 39
arsaces
  • 39
  • 6
  • 1
    Not `Get-ChildItem`, but `Rename-Item`. Use `-LiteralPath` instead. – Abraham Zinala Jul 26 '22 at 19:05
  • 1
    The `-Path` parameter of provider (file-handling) cmdlets (which the first _positional_ argument implicitly binds to), expects _wildcard_ expressions. Because PowerShell's wildcard language also supports expressions such as `[a-z]`, paths meant to be _literal_ ones are misinterpreted if they happen to contain `[` chars. To pass a literal path as such, use the `-LiteralPath` parameter explicitly. Alternatively, pass a file-information object such as produced by `Get-ChildItem` _via the pipeline_ to a provider cmdlet, which also binds to `-LiteralPath`. – mklement0 Jul 26 '22 at 19:19
  • 1
    As an aside: you can simplify and speed up your pipeline by piping directly to `Rename-Item` and using a _delay-bind script block_, which implicitly bypasses the `-Path` / `-LiteralPath` problem: `gci C:\Users\Documents\SAMPLE\* -in *.mp4,*.mkv -Recurse | rename-item –Newname { $_.basename + ' (TEST)' + $_.extension }` - see [this answer](https://stackoverflow.com/a/53575423/45375) for an explanation. – mklement0 Jul 26 '22 at 19:33

1 Answers1

1

Debugging tip: when you have code issues and are using the pipeline, rewrite the code not to use the pipeline, break the problem down into steps, and insert debugging aids to help troubleshoot. For example, it could be Write-Host, saving to temp variables, etc.

-LiteralPath

Specify the path with the -LiteralPath parameter:

[PS]> gci -LiteralPath '.\Music\Artist - Name\Album Name [Disc 1]\'

To improve the ability of Windows PowerShell 3.0 to interpret and correctly handle special characters, the LiteralPath parameter, which handles special characters in paths, is valid on almost all cmdlets that have a Path parameter

See the following Q&A for more about square brackets & escaping:

  • 2
    Nice, but to avoid confusion: the OP's problem is with `Rename-Item`, not `Get-ChildItem`. The linked post is about a slightly different use case: incorporating a verbatim `[` into a _wildcard expression_. – mklement0 Jul 26 '22 at 19:36