powershell - Rename file with powershell (variable file name structure)
问题描述
Currently I'am facing an issue in renaming file names with powershell. I'am actually able to rename files in a particular folder, however if the structure is different the command fails.
Example files:
test file - 1234 - copy.docx
test file - 1234.pdf
I was running the following command:
Get-ChildItem <location> -file | foreach {
Rename-Item -Path $_.FullName -NewName ($_.Name.Split("-")[0] + $_.Extension) }
I want to keep the filename before the last "-". But if I run my command, I always get file name before the first "-".
Any advice for a better approach?
解决方案
Most straightforward approach:
Get-ChildItem <location> -File | Rename-Item -NewName {
$index = $_.BaseName.LastIndexOf("-")
if ($index -ge 0) {
$_.BaseName.Substring(0, $index).Trim() + $_.Extension
}
else { $_.Name }
}
Regex replace:
Get-ChildItem <location> -File |
Rename-Item -NewName {($_.BaseName -replace '(.*)-.*', '$1').Trim() + $_.Extension}
推荐阅读
- reactjs - React Router:传递给子节点的选择性路由道具
- python - 从数组中删除一行
- javascript - 为什么 setInterval 在使用 Date 方法时返回相同的值
- django - 为什么 Django Crispy Forms 会抛出“模块‘django.forms.forms’没有属性‘BoundField’”
- sql - 在 SQLite 中使用 CASE 语句和 SELECT 来排除显示某些结果
- php - 如何使用一个查询 php 更新多个表?
- java - 如何在测试中静态获取spring上下文或bean?
- uwp - 用于滑动视图的 UWP CustomRenderer 无法使用 Element.Open(OpenSwipeItem) 打开
- c# - (取消订阅)事件的有效替代方案
- themes - iTerm2 的 JetBrains Intellij macOS 轻主题