"(" char does not work in PowerShell

I can't get this to work. It is not pleasant "(" char;

how can i fix this?

 Dir | Rename-Item -NewName { $_.name -replace "(","" }

How to handle this type of special character in PowerShell?

+3
source share
3 answers

You have a great explanation of the exact cause of your problem from @vonPryze, but there is a much simpler solution. The operator -replaceuses regular expressions that require escaping, but the string method .Replace()uses only strings. Therefore, if you do not need a regular expression, just use this method and you have nothing to hide:

dir | rename-item -NewName { $_.name.Replace("(","") }
+9
source

. , , , ,

for($i=0;$i -le 4; ++$i) { set-content -path $("file($i).txt" -f $i) -value $i }
Output:
gci
    Directory: C:\temp\foo
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         17.2.2014     10:34          3 file(0).txt
-a---         17.2.2014     10:34          3 file(1).txt
-a---         17.2.2014     10:34          3 file(2).txt
-a---         17.2.2014     10:34          3 file(3).txt
-a---         17.2.2014     10:34          3 file(4).txt

, , , , ,

Dir | Rename-Item -NewName { $_.name -replace "(","" }

Rename-Item : The input to the script block for parameter 'NewName' failed.
Invalid regular expression pattern: (.
At line:1 char:27
+ Dir | Rename-Item -NewName <<<<  { $_.name -replace "(","" }
    + CategoryInfo          : InvalidArgument: (file(0).txt:PSObject) [Rename-Item], ParameterBind   ingException
    + FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.Re   nameItemCommand

Oops! , . , -replace , !

-replace , . \, . , , , .Net Regex [Regex]::Excape(). ,

Dir | Rename-Item -NewName { $_.name -replace [regex]::escape("("),"" }
Output:
ls
    Directory: C:\temp\foo
Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         17.2.2014     10:34          3 file0).txt
-a---         17.2.2014     10:34          3 file1).txt
-a---         17.2.2014     10:34          3 file2).txt
-a---         17.2.2014     10:34          3 file3).txt
-a---         17.2.2014     10:34          3 file4).txt
+9
Dir | Rename-Item -NewName { $_.name -replace "\(","" } # This works 
+4
source

All Articles