Author Posts

July 26, 2018 at 9:37 am

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!

July 26, 2018 at 1:26 pm

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

July 26, 2018 at 1:28 pm

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 😉

July 26, 2018 at 1:36 pm

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!

July 26, 2018 at 1:37 pm

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.

July 26, 2018 at 2:13 pm

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

July 26, 2018 at 2:20 pm

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.

July 26, 2018 at 2:21 pm

(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)

July 27, 2018 at 5:59 pm

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