qmckinsey
qmckinsey

Reputation: 305

Powershell replacing periods

Can anyone tell me if they think there is something wrong with this Powershell script.

Dir | 
where {$_.extension -eq ".txt"} | 
Rename-Item –NewName { $_.name –replace “.“,”-” }

For each text file in the current directory, I'm trying to replace all periods in the file names with hyphens. Thanks ahead of time.

Upvotes: 2

Views: 19387

Answers (3)

Frode F.
Frode F.

Reputation: 54881

As the others have said, -replace uses regex (and "." is a special character in regex). However, their solutions are forgetting about the fileextension and they are acutally removing it. ex. "test.txt" becomes "test-txt" (no extension). A better solution would be:

dir -Filter *.txt | Rename-Item -NewName { $_.BaseName.replace(".","-") + $_.Extension }

This also uses -Filter to pick out only files ending with ".txt" which is faster then comparing with where.

Upvotes: 8

wullxz
wullxz

Reputation: 19450

The name property of a file object in powershell is of type string.
That means, you could also use the static string method replace like follows and don't care about regex' reserved characters:

dir | ? { $_.extension -eq ".txt" } | rename-item -newname { $_.name.replace(".","-") }

Upvotes: 1

BartekB
BartekB

Reputation: 8650

-replace operates on regex, you need to escape '.':

rename-item -NewName { $_.Name -replace '\.', '-' }

Otherwise you will end up with '----' name...

Upvotes: 7

Related Questions