我需要在PowerShell中重新排列和重命名一堆文件的帮助。我想从以下位置更改:
YYYY_项目名称_城市_类别。jpg
to
YYYY _ Category _项目名称_City.jpg
当然,年份,类别,项目名称和城市都不同。
请谨慎,我是PowerShell和regex的新手。
假设我们有一个类似这样的项目:
get-item '.\YYYY_Project name_City_Category.jpg'
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 6/8/2020 10:12 AM 8 YYYY_Project name_City_Category.jpg
这是一个FileInfo
对象,它具有许多属性,其中一个是BaseName
,它为我们提供了不带扩展名的文件名。
PS> $file = get-item '.\YYYY_Project name_City_Category.jpg'
PS> $File.BaseName
YYYY_Project name_City_Category
我们可以在BaseName属性上调用.Split()
方法,以对_
下划线字符的每个实例进行分割,如下所示:
PS> $File.BaseName.Split('_')
YYYY
Project name
City
Category
然后我们可以将它们分配给这样的变量:
$FileSegments = $File.BaseName.Split('_')
$YearPart = $FileSegments[0]
$ProjPart = $FileSegments[1]
$CityPart = $FileSegments[2]
$CatgPart = $FileSegments[3]
然后我们可以按照所需的顺序重新组装它们,如下所示:
$newName = $YearPart + "_" + $CatgPart + "_" + $ProjPart + "_" + $CityPart + $file.Extension
write-host $newName
YYYY_Category_Project name_City.jpg
所以,您将像这样将它们放在一起。如果您喜欢结果,请删除-WhatIf
$files = Get-ChildItem C:\PathTo\Your\Directory\*.jpg
ForEach ($file in $files){
$FileSegments = $File.BaseName.Split('_')
$YearPart = $FileSegments[0]
$ProjPart = $FileSegments[1]
$CityPart = $FileSegments[2]
$CatgPart = $FileSegments[3]
$newName = $YearPart + "_" + $CatgPart + "_" + $ProjPart + "_" + $CityPart + $file.Extension
write-host $newName
Rename-Item -Path $file.FullName -NewName $newName -WhatIf
}
您不需要为此使用复杂的Regex,只需对如何使用Get-ChildItem获取文件夹中的文件以及Rename-Item的工作原理有所了解。
这样的事情应该做
$sourcePath = 'Folder\To\Where\The\Files\Are'
Get-ChildItem -Path $sourcePath -Filter '*.jpg' -File | Rename-Item -NewName {
# split the file's BaseName into 4 pieces at the underscore
$year, $project, $city, $category = $_.BaseName -split '_', 4
# use the -f Format operator to stitch the parts together in a new order
# see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_operators?view=powershell-5.1#format-operator--f
'{0}_{1}_{2}_{3}{4}' -f $year, $category, $project, $city, $_.Extension
}
一个拆分和合并想法的衬里版本:
dir *_*_*_*.jpg | ren -new {((($_.basename -split '_')[0,3,1,2]) -join '_') +'.jpg'} -whatif
What if: Performing the operation "Rename File" on target
"Item: C:\Users\admin\foo\YYYY_Project name_City_Category.jpg
Destination: C:\Users\admin\foo\YYYY_Category_Project name_City.jpg".