Getting an Error when I try to change file name in PowerShell -


i found similar commands these online. want replace parenthesis in file names either space or empty string.

the files i'm trying change following:

nehemiah (1).mp3 nehemiah (2).mp3 nehemiah (11).mp3 

really i'd them following:

nehemiah 01.mp3 nehemiah 02.mp3 nehemiah 11.mp3 

here scripts i've tried.

dir | rename-item –newname { $_.name –replace “(“,”” } dir *.mp3 | rename-item -newname {  $_.name  -replace " ("," "  } 

neither of these work.

here error message i'm getting.

rename-item : input script block parameter 'newname' failed. regular expression pattern ( not valid. @ line:1 char:34 + dir *.mp3 | rename-item -newname { $_.name -replace " ("," " } + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + categoryinfo : invalidargument: (c:\users...ehemiah (1).mp3:psobject) [rename-item], parameter ndingexception + fullyqualifiederrorid : scriptblockargumentinvocationfailed,microsoft.powershell.commands.renameitemcommand

as have seen in comments mathias r jessen -replace supports regular expressions , need account that. static method escape can automatically escape regex meta characters in strings can appear more readable , function see them.

i did manage find this on msdn talks characters escaped using [regex]::escape():

escapes minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, , white space) replacing them escape codes. instructs regular expression engine interpret these characters literally rather metacharacters.

however since don't need using regex here suggest use string method .replace() accomplish same without overhead.

get-childitem "*.mp3" | rename-item -newname {($_.name).replace(" ("," ")} 

character padding changes things little though. op regex there since lot easier splitting strings , putting them together.

get-childitem "*.mp3" |      where-object{$_.name -match "\((\d+)\)"}     rename-item -newname {         [regex]::replace($_.name,"\((\d+)\)",{param($match) ($match.groups[1].value).padleft(2,"0")})     } 

thanks petseral helping backreference replacement solution.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -