Long Truong Long Truong - 3 months ago 32
PowerShell Question

Renaming a file name to the next incremental number with powershell script

I have a question with powershell script. I have a daily task scheduler and it exports the file with the name 12122_000000.txt and store it on C:\ drive. I'm also have another Report folder at C:\Report. In that Report folder, I have a lot of file with the name 12122_000001.txt, 12122_000002.txt, 12122_0000003.txt,12122_0000004.txt and so forth.

I would like to have a script that will check the Report folder to find the latest file name. Then, moving the file name 12122_000000.txt on C:\ to C:\Report and rename it with the highest name increase 1. The format of filename must be 12122_xxxxxx.txt

I have tried to write the script but it didn't work. Please help me to gain my knowledge of powershell.

$SourceFile = "C:\12122_000000.txt"
$DestinationFolder = "C:\Report"
if (Test-Path $SourceFile)
{
$latest = Get-ChildItem -Path $DestinationFolder| Sort-Object Name -Descending | Select-Object -First 1
$i = 1
Move-Item -path $SourceFile -destination $latest.basename + $i++ + ".txt")
}


Thanks

Answer

Here is an easy way to increment this filename and move the file:

$SourceFile = "C:\12122_000000.txt"
$DestinationFolder = "C:\Report"
if (Test-Path $SourceFile)
{ 
    $latest = Get-ChildItem -Path $DestinationFolder| Sort-Object Name -Descending | Select-Object -First 1
    #split the latest filename, increment the number, then re-assemble new filename:
    $newFileName = $latest.BaseName.Split('_')[0] + "_" + ([int]$latest.BaseName.Split('_')[1] + 1).ToString().PadLeft(6,"0") + $latest.Extension
    Move-Item -path $SourceFile -destination $DestinationFolder"\"$newFileName
}