找不到更好的循环解决方案


我在PowerShell中有一个任务,检查文件名,如果存在,则在

末尾添加数字,如果存在,则在第一次检查后,我们将数字增加一。

我在将数字增加 1 时遇到麻烦。

$path = 'D:TestTestFile.zip'
if (Test-Path $path) {
    # File exists, append number
    $fileSeed = 0
    do {
        $path = $path  -replace ".zip$"
        $path += ''
        $fileSeed++
        $path = "$path$fileSeed.zip"
    } until ( ! (Test-Path $path) )
} else {
    $path
}

前段时间,我为此编写了一个叫做 Get-UniqueFileName 的小函数。

function Get-UniqueFileName {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, Position = 0)]
        [Alias('FullName')]
        [string]$Path
    )
    $directory = [System.IO.Path]::GetDirectoryName($Path)
    $baseName  = [System.IO.Path]::GetFileNameWithoutExtension($Path)
    $extension = [System.IO.Path]::GetExtension($Path)    # this includes the dot
    # get an array of all files with the same extension currently in the directory
    $allFiles  = @(Get-ChildItem $directory -File -Filter "$baseName*$extension" | Select-Object -ExpandProperty Name)
    # construct the possible new file name (just the name, not hte full path and name)
    $newFile = $baseName + $extension
    $seed = 1
    while ($allFiles -contains $newFile) {
        # add the seed value between brackets. (you can ofcourse leave them out if you like)
        $newFile = "{0}({1}){2}" -f $baseName, $seed, $extension
        $seed++
    }
    # return the full path and filename
    return Join-Path -Path $directory -ChildPath $newFile
}

像这样使用它:

Get-UniqueFileName -Path 'D:TestTestFile.zip'

如果目录D:Test已经包含一个名为 TestFile.zip 的文件和另一个名为 TestFile(1).zip 的文件,它将返回D:TestTestFile(2).zip

最新更新