如果存在重复文件,如何使用powershell重命名文件?
我一直在使用此代码重命名文件 例如,569_SOM_TEST.jpg到569 但如果存在569_TOB_TEST.jpg,它会给出一个错误重命名项:当文件已经存在时,无法创建该文件 我想让它变成569-1如果存在重复文件,如何使用powershell重命名文件?,powershell,Powershell,我一直在使用此代码重命名文件 例如,569_SOM_TEST.jpg到569 但如果存在569_TOB_TEST.jpg,它会给出一个错误重命名项:当文件已经存在时,无法创建该文件 我想让它变成569-1 如何完成此操作?为了防止重命名冲突,可以在脚本顶部放置以下帮助程序函数: Get-ChildItem -Filter *_* | Foreach-Object -Process { $NewName = [Regex]::Match($_.Name,"^[^ _]*&quo
如何完成此操作?为了防止重命名冲突,可以在脚本顶部放置以下帮助程序函数:
Get-ChildItem -Filter *_* | Foreach-Object -Process {
$NewName = [Regex]::Match($_.Name,"^[^ _]*").Value +'.jpg'
$_ | Rename-Item -NewName $NewName
}
这将确保任何建议的新文件名都会在其基本名称后附加一个尚未使用的索引号。是新文件名,因此您可能不知道这一点,但通常通过单击✓ 左边的图标。这将帮助其他有类似问题的人更容易找到它,并有助于激励人们回答你的问题。
function Rename-FileUnique {
# Renames a file. If a file with that name already exists,
# the function will create a unique filename by appending '(x)' after the
# name, but before the extension. The 'x' is a numeric value.
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
[string]$Path,
[Parameter(Mandatory = $true, Position = 1)]
[string]$NewName,
[switch]$PassThru
)
# Throw a bit nicer error than with [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
if (!(Test-Path -Path $Path -PathType Leaf)){
Throw [System.IO.FileNotFoundException] "Rename-FileUnique: The file '$Path' could not be found."
}
# split the new filename into a basename and an extension variable
$baseName = [System.IO.Path]::GetFileNameWithoutExtension($NewName)
$extension = [System.IO.Path]::GetExtension($NewName) # this includes the dot
$folder = Split-Path -Path $Path -Parent
# get an array of all filenames (name only) of the files with a similar name already present in the folder
$allFiles = @(Get-ChildItem $folder -Filter "$baseName*$extension" -File | Select-Object -ExpandProperty Name)
# for PowerShell version < 3.0 use this
# $allFiles = @(Get-ChildItem $folder -Filter "$baseName*$extension" | Where-Object { !($_.PSIsContainer) } | Select-Object -ExpandProperty Name)
# construct the new filename / strip the path from the file name
$NewName = $baseName + $extension # or use $NewName = Split-Path $NewName -Leaf
if ($allFiles.Count) {
$count = 1
while ($allFiles -contains $NewName) {
$NewName = "{0}-{1}{2}" -f $baseName, $count++, $extension
}
}
Write-Verbose "Renaming '$Path' to '$NewName'"
Rename-Item -Path $Path -NewName $NewName -Force -PassThru:$PassThru
}
Get-ChildItem -Filter '*_*.jpg' | Foreach-Object {
# create the proposed new filename
$newName = '{0}.jpg' -f ($_.Name -split '_')[0]
$_ | Rename-FileUnique -NewName $newName
}