Reputation: 287
I sincerely apologize if my question seems too easy. I'm completely new to PowerShell and I'm still learning the basics.
I have a folder E:\LastMonthBackup
Where SQL Server everyday adds one new file named ProjectBackup.bak
I need a PowerShell script that could rename this newly added file by adding the date when the file was created.
So in essence I want each new file to be named ProjectBackup_Year_Month_Day.bak
I don't want the script to touch the files which already have dates in their names. Only this one new ProjectBackup.bak file should be renamed.
Could you please help me to write such script?
I found a related question here, but when I tried applying solution from it in my script it didn't work or maybe I just messed up something. I am totally new to PowerShell so any help will be greatly appreciated.
Upvotes: 1
Views: 765
Reputation: 58931
If its only one file you want to rename to your pattern, you can try this:
$fileToRename = "E:\LastMonthBackup\ProjectBackup.bak"
if (Test-Path $fileToRename)
{
$fileName = [system.io.path]::GetFileNameWithoutExtension($fileToRename)
$dateSuffix = get-date -Format 'yyyy_MM_dd'
$fileExtension = [system.io.path]::GetExtension($fileToRename)
$newFileName = '{0}_{1}{2}' -f $fileName, $dateSuffix, $fileExtension
Rename-Item -Path $fileToRename -NewName $newFileName
}
If the file $fileToRename
exisits, the script determines the filename ProjectBackup
, the date with format yyyy_MM_dd
and the file extension .bak
and formats the new string. Finally, it renames the file to the new name.
Upvotes: 3