Powershell 更换周期 [英] Powershell replacing periods
问题描述
谁能告诉我他们是否认为这个 Powershell 脚本有问题.
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.
推荐答案
正如其他人所说,-replace
使用正则表达式(."是正则表达式中的特殊字符).然而,他们的解决方案忘记了文件扩展名,他们实际上正在删除它.前任.test.txt"变成test-txt"(无扩展名).更好的解决方案是:
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 }
这也使用 -Filter 只挑选以.txt"结尾的文件,这比与 where 比较要快.
This also uses -Filter to pick out only files ending with ".txt" which is faster then comparing with where.
这篇关于Powershell 更换周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!