Create Filename Incrementing Number

Welcome Forums General PowerShell Q&A Create Filename Incrementing Number

This topic contains 8 replies, has 3 voices, and was last updated by

 
Participant
3 months, 3 weeks ago.

  • Author
    Posts
  • #105295
    Dan

    Participant
    Points: 0
    Rank: Member

    Hi all,

    Sorry to post on here but i've been looking for hours trying to find this solution but nothing seems to work,

    The easy way to describe it is I need to be able to check if a file exists in a folder, if it does then create a new file with the next number up.

    For example if F00001.txt exists then it creates F00002.txt, i found a solution that works up to F00009.txt but when it gets to the next one it renames it to F000010 when i need it to be F00010 so it retains the same amount of characters.

    $SourceFile = "C:\Temp\File.txt"
    $DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"

    If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
    $i += 1
    $DestinationFile = "C:\Temp\NonexistentDirectory\File$i.txt"
    }
    } Else {
    New-Item -ItemType File -Path $DestinationFile -Force
    }

    Copy-Item -Path $SourceFile -Destination $DestinationFile -Force

    Your help would be massively appreciated!

  • #105316

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    This is not a PESTER question. Moving to the correct forum.

  • #105319

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    As-is, your entire logic will only execute if the file exists in the first place. Was that the intent? You don't mention what isn't working about your code, so it's a little difficult to offer help 😉

  • #105332
    Dan

    Participant
    Points: 0
    Rank: Member

    thanks for the reply! yep the first file will exist and i need to increment from the first number onwards.

    The part that doesnt work is when it gets to the 10th number it goes to FR000010 rather than FR00010 so it adds another character in the amount of numbers needed if that makes sense...

    Thanks!

  • #105335

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    Ah. You're going to probably need to use a formatted string, using the -f operator, then. You'll need to read up on the docs for an appropriate formatting directive.

  • #105353
    Dan

    Participant
    Points: 0
    Rank: Member

    yeah i've looked for ages and wasn't sure if anyone else had any experience with it 🙁

  • #105355

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    Well, start here. https://social.technet.microsoft.com/wiki/contents/articles/7855.powershell-using-the-f-format-operator.aspx

    Basically,

    $filename = "F" -f $i
    

    It puts $i into the string at whatever location you specify. As above, I didn't specify, so it'll just be "F."

    "F{0:N3}"

    Specifies the first insert position, zero, which s where $i would go. N3 says "three digits to the left." You can play with the formatting strings to get what you want.

  • #105358

    Keymaster
    Points: 1,638
    Helping HandTeam Member
    Rank: Community Hero

    (FWIW, I just Googled "PowerShell formatting operator" to find that link; there were many others including the official .NET documentation, but that article seems concise)

  • #105500

    Participant
    Points: 160
    Helping Hand
    Rank: Participant

    You can use padleft to pad characters, like a zero. This code looks for files starting with F, which is a bit weak, but if you require something more specific you could use a regex to be more specific checking the basename:

    PS C:\Users\Rob> "F00004" -match "^F[0-9]{5}$"
    True
    
    PS C:\Users\Rob> "Frank" -match "^F[0-9]{5}$"
    False
    

    To keep the assumption that these are the only files in the directory, you could do something like below. In the output, I'm just running the script over and over. I've tried to add comments and output to show how the script is working:

    $path = "C:\Scripts\Test"
    $baseName = "F"
    
    $files = Get-ChildItem -Path ("{0}\{1}*" -f $path, $baseName)
    
    if ($files) {
        "Existing files found"
        #Create custom column by removing the F and making it a integer, so only a number is returned
        $numbers = $files | Select @{Name="Number";Expression={[int]$_.BaseName.Replace($baseName, "")}}
        "Found {0} existing files" -f $files.Count
        #Take the number, sort descending, get the first value and then increment by 1
        $max = ($numbers | Sort-Object -Property Number -Descending | Select -First 1 -ExpandProperty Number) + 1
        "The next number is {0}" -f $max
        #Use padding to pad zeros up to 5 characters
        $file = "F{0}.txt" -f $max.ToString().PadLeft(5,'0')
        "Incrementing {0} to generate file {1}" -f $max, $file
        New-Item -Path $path -Name $file -ItemType File
    
    }
    else {
        $file = ("{0}{1}.txt" -f $baseName, "1".ToString().PadLeft(5,'0'))
        "Creating first file {0}" -f $file
    
        New-Item -Path $path -Name $file -ItemType File
    }
    

    Output:

    PS C:\Users\Rob> C:\Users\Rob\Desktop\test.ps1
    Existing files found
    Found 8 existing files
    The next number is 9
    Incrementing 9 to generate file F00009.txt
    
    
        Directory: C:\Scripts\Test
    
    
    Mode                LastWriteTime         Length Name                                                                                                                                             
    ----                -------------         ------ ----                                                                                                                                             
    -a----        7/27/2018   1:45 PM              0 F00009.txt                                                                                                                                       
    
    
    
    PS C:\Users\Rob> C:\Users\Rob\Desktop\test.ps1
    Existing files found
    Found 9 existing files
    The next number is 10
    Incrementing 10 to generate file F00010.txt
    
    
        Directory: C:\Scripts\Test
    
    
    Mode                LastWriteTime         Length Name                                                                                                                                             
    ----                -------------         ------ ----                                                                                                                                             
    -a----        7/27/2018   1:45 PM              0 F00010.txt                                                                                                                                       
    
    
    
    PS C:\Users\Rob> C:\Users\Rob\Desktop\test.ps1
    Existing files found
    Found 10 existing files
    The next number is 11
    Incrementing 11 to generate file F00011.txt
    
    
        Directory: C:\Scripts\Test
    
    
    Mode                LastWriteTime         Length Name                                                                                                                                             
    ----                -------------         ------ ----                                                                                                                                             
    -a----        7/27/2018   1:45 PM              0 F00011.txt    
    
    
    
    		
    	

The topic ‘Create Filename Incrementing Number’ is closed to new replies.