首页 > 解决方案 > How would I change multiple filenames in Powershell?

问题描述

I am trying to remove parts of a name "- xx_xx" from the end of multiple files. I'm using this and it works well.

dir | Rename-Item -NewName { $_.Name -replace " - xx_xx","" }

However, there are other parts like:

" - yy_yy" " - zz_zz"

What can I do to remove all of these at once instead of running it again and again changing the part of the name I want removed?

标签: powershellrename

解决方案


最简单的方法

如果需要,您可以继续串-replace语句直到奶牛回家。

$myLongFileName = "Something xx_xx yy_yy zz_zz" -replace "xx_xx","" -replace "yy_yy"

更简洁的语法

如果每个文件都有这些,你也可以制作一个你想要替换的数组,就像这样,只是用逗号分隔它们。

$stuffWeDontWantInOurFile =@("xx_xx", "yy_yy", "zz_zz")
$myLongFileName -replace $stuffWeDontWantInOurFile, ""

还有一种方式

如果您的文件元素由空格或破折号或可预测的东西分隔,您可以在其上拆分文件名。

$myLongFileName = "Something xx_xx yy_yy zz_zz" 

PS> $myLongFileName.Split()
Something
xx_xx
yy_yy
zz_zz

PS> $myLongFileName.Split()[0] #select just the first piece
Something

对于空格,您使用Spit()其中没有重载的方法。

如果它是破折号或其他字符,你会像这样提供它Split("-")。在这些技术之间,你应该能够做你想做的事情。


推荐阅读