PowerShell provides Move-Item and Rename-Item cmdlets to move file and rename it with the date. Use the Get-Date cmdlet to get the current date and append it to the file.
PowerShell provides many cmdlets to manage files and folders in your system.
In this article, we will discuss how to rename and move files with the current date appended to them using the Rename-Item, Move-Item, and Get-Date cmdlets in PowerShell.
Renaming a File with the Current Date
Use the Rename-Item cmdlet in PowerShell to rename a file by appending the current date to its name.
$currentDate = Get-Date -Format yyyy-MM-dd $sourceFile = "D:\PS\ad.txt" $destinationFile = "D:\PS\ad_$currentDate.txt" Rename-Item -Path $sourceFile -NewName $destinationFile
In the above PowerShell script, the Get-Date cmdlet gets the current date time and stores it in the
$currentDate variable. The
$sourcePath variable contains the file name and
$destinationFile contains the file name and current date appended to it.
The Rename-Item uses the
-Path parameter to specify the old file name and the
-NewName parameter to specify the new file with the current date. It renames the file ad.txt to ad_2023-04-09.txt, assuming the current date is April 09, 2023.
Move File and Rename a File with the Current Date
Use the Move-Item cmdlet in PowerShell to move the file to a different folder and rename it with the current date.
# Get the current date $currentDate = Get-Date -Format yyyy-mm-dd # Source file name $sourceFile = "D:\PS\ad.txt" # Append the Current date to file name $destinationFile = "ad_$currentDate.txt" # Destination folder path $destinationFolder = "D:\PS\AD" # Move file and rename the file Move-Item -Path $sourceFile -Destination "$destinationFolder\$destinationFile" # Get the items from the destination folder Get-ChildItem -Path D:\PS\AD\ | Select-Object -First 1
In the above PowerShell script, the Move-Item cmdlet uses the
-Path parameter to specify the source file name and the
-Destination parameter to specify the destination folder path. It moves the file and renames the file with the current date.
The Get-ChildItem cmdlet retrieves items from the destination folder path.
The output of the above PowerShell script after moving and renaming a file with the current date is:
Cool Tip: How to create a log file with date time in PowerShell!
I hope the above article on how to move files and rename them with the current date using the Move-Item cmdlet in PowerShell is helpful to you.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.