Powershell - 从 "Group-Object" 输出中重命名文件

Powershell -Rename files from "Group-Object" output

所以我有 150 个文件夹,其中包含 100 个这样命名的文件.. M10001662_3269506_DVLA_Original_Complete_archived_201208_2226.pdf M10001662_3269506_DVLA_Original_Complete_archived_201209_2203.pdf M10001662_3269506_DVLA_Original_Complete_archived_201210_2231.pdf M10001662_3269506_DVLA_Original_Complete_archived_201211_2202.pdf

EDIT There are about 10 different file names, all with "_archived_YYYYMMDD_HHMM.pdf" added to the end. I just need one (they are all identical, so anyone will do) of each file without the "_archived_YYYYMMDD_HHMM.pdf" on the end. NB: Theo has asked for desired output - From many files like M10001662_3269506_DVLA_Original_Complete_archived_201208_2226.pdf To One file like M10001662_3269506_DVLA_Original_Complete.new

Was looking to rename the files I want to keep with *.new Then delete all *.pdf files (Just as I know how to do that) and finally rename the .new files back to *.pdf Leaving me with only one of each file.

Hope this has made it clearer, END EDIT

我有以下代码,它为我提供了我想要保留的文件名,但我实际上无法操作重命名位..

# Remove duplicate files - based on name/string search
# set the rootfolder to search
$dir = 'O:\UKCH-DATA\Contact Centre - Main - DVLA\_case_files_archive\M10001662'
# loop through the directories directly under $dir
Get-ChildItem -Path $dir -Filter "*.pdf" |
Group-Object -property {$_.BaseName.split('archived', 2)[0]} | 
ForEach-Object { $_.Group | Select-Object -First 1} 
#Write-Output $Filename.VersionInfo |
#Rename-Item $Filename.VersionInfo -NewName -replace ("\.pdf", ".new")

重命名的第一部分遇到问题,请帮助

你可以做得更简单:

Get-ChildItem -Path $dir -Filter "*.pdf" |
  Group-Object -property { $_.BaseName.split('archived', 2)[0] } | foreach {
    # rename the file to keep (the 1st file from the group)
    $_.Group | select -First 1 | Rename-Item -NewName ($_.Name + ".pdf")
    # delete the others:
    $_.Group | select -Skip 1 | Remove-Item
}

对于 重命名 部分,您可以使用 :

# ... represents your command from the question.
... | Rename-Item -NewName { $_.Name -replace '_archived.+', '.new' } -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

注意:我假设您也想从文件名中删除 _archived* 部分,这就是上面的 -replace operation 所做的;如果您只想将文件扩展名从 .pdf 更改为 .new,请使用 { $_.BaseName + '.new' }.


由于上面更改了您要保留的文件的文件扩展名,您可以删除留下的.pdf个文件:

Remove-Item -Path $dir\*.pdf -WhatIf