Home > Mobile >  If testfile1.log exists, create testfile2.log, and so on.. - PowerShell
If testfile1.log exists, create testfile2.log, and so on.. - PowerShell

Time:01-16

My PowerShell script creates a log file, but when I run the script for the second time, it tells me that the testfile1.log file already exists.

How do I make the script if it finds testfile1.log, it creates testfile2.log, and if this also exists, it creates testfile3.log, and so on..

New-Item -Path $path -Name "testfile1.log" -ItemType "file"

CodePudding user response:

You could do it this way, first get all the files in the desired path and sort them by the ending digits on their name. If no files are found create the testfile1.log, if there were files found, get the last sorted file (the one with the highest ending digit) extract the ending digits and add 1 to the count and use it to create the new file.

$files = Get-ChildItem $path -Filter testfile*.log | Sort-Object {
  $_.BaseName -replace '\D' -as [int]
}

if(-not $files)
{
  New-Item -Path $path -Name "testfile1.log" -ItemType File
}
else
{
  [int]$number = $files[-1].BaseName -replace '\D'
  $number  
  New-Item -Path $path -Name "testfile$number.log" -ItemType File
}

CodePudding user response:

An alternative method, based on this answer could be

$path  = 'D:\Test'
$log   = 'testfile'
$index = ((Get-ChildItem -Path $path -Filter "$log*.log" -File |
    Where-Object { $_.BaseName -match "$log\d $" } |
    Select-Object @{Name = 'index'; Expression = {[int]($_.BaseName -replace '\D')}}).index |
    Measure-Object -Maximum).Maximum   1
# create the new file
New-Item -Path (Join-Path -Path $path -ChildPath "$log${index}.log") -ItemType File

CodePudding user response:

A concise solution that also builds on this answer (see there for an explanation of the core technique):

$path = '.'                       # Output dir.
$nameTemplate = 'testfile{0}.log' # {0} is the sequence-number placeholder
New-Item -ItemType File -Path $path -Name (
  $nameTemplate -f (1   (
    # Find all existing log files
    Get-ChildItem (Join-Path $path $nameTemplate.Replace('{0}', '*')) | 
      Measure-Object -Maximum {
        # Extract the embedded sequence number.
        $_.Name -replace [regex]::Escape($nameTemplate).Replace('\{0}', '(\d )'), '$1'
      }
  ).Maximum)
) -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

Note:

  • The above uses a complex -replace operation to reliably extract the sequence number from existing file names; if you know that that only one number is present in each given file name, $_.BaseName -replace '\D' (removing all non-digit characters) will do in the Measure-Object call above.

  • If you wanted to use zero-padded, fixed-width sequence numbers, you can adjust (all occurrences of) the {0} placeholder accordingly; e.g, to create sequence numbers 01, 02, ... 99, use {0:00} - see the Composite formatting help topic, which describes the string formatting language also used by PowerShell's -foperator

  •  Tags:  
  • Related