问题
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.
回答1:
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.
回答2:
-replace operates on regex, you need to escape '.':
rename-item -NewName { $_.Name -replace '\.', '-' }
Otherwise you will end up with '----' name...
回答3:
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(".","-") }
来源:https://stackoverflow.com/questions/14541980/powershell-replacing-periods