Append Timestamp to File Names–Powershell


You can rename text files in a folder with a simple replace to append timestamp to file names through powershell script.
There is also another way to control file extension to change file name as well.

From Powershell window:



 --Option with  replace .txt with appended timestamp
 Get-ChildItem c:\temp\src\*.* | rename-item -NewName {$_.name -replace ".txt",((get-date).ToString("_yyyyMMdd_HHmmss")+".txt")}
 
 --Option insert timestamp before .txt extension

ls c:\temp\src\*.* | ? { !$_.PSIsContainer   -and   $_.extension -eq '.txt' } |   ren -NewName { "$($_.BaseName) $(get-date -format "yyyymm%d%H%M%S")$($_.extension) "  }  




 

If you want to run powershell from SSMS, you can use xp_cmdshell to call powershell.exe

  
  --## replace .txt with appended timestamp
xp_cmdshell 'PowerShell.exe -noprofile -command  "Get-ChildItem c:\temp\src\*.* | rename-item -NewName {$_.name -replace ''.txt'',((get-date).ToString(''_yyyyMMdd_HHmmss'')+''.txt'')} "'


--## insert timestamp before .txt extension
xp_cmdshell 'PowerShell.exe -noprofile -command  "ls c:\temp\src\*.* | ? { !$_.PSIsContainer  -and  $_.extension -eq ''.txt'' } |   ren -NewName { \"$($_.BaseName) $(get-date -format \"yyyymm%d%H%M%S\")$($_.extension) \"  }   "'
--Or
xp_cmdshell 'PowerShell.exe -noprofile -command  "ls c:\temp\src\*.* | ? { !$_.PSIsContainer  -and  $_.extension -eq ''.txt'' } |   ren -NewName { \"$($_.BaseName) $(get-date -format ''_yyyyMMdd_HHmmss'')$($_.extension) \"  }   "'


 
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s