Не могу найти лучшее решение с петлями - PullRequest
0 голосов
/ 15 января 2019

У меня есть задача в PowerShell, которая проверяет имя файла, и если он существует, добавьте номер в конце, и если он существует после первой проверки, мы увеличим число на единицу.

У меня проблема с увеличением числа на 1.

$path = 'D:\Test\TestFile.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
}

1 Ответ

0 голосов
/ 15 января 2019

Некоторое время назад я написал для этого небольшую функцию под названием 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:\Test\TestFile.zip'

Если каталог D:\Test уже содержит файл с именем TestFile.zip и другой файл с именем TestFile(1).zip, он вернет D:\Test\TestFile(2).zip

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...