Copy file with containing date time

hernandy 1 Reputation point

Hi All,

I have some script to copy the file on the directory with filename containing date (MMddyyy).asc , let's say the file as follows :

  • 11022021.asc
  • 11032021.asc
  • 11042021.asc

And i need to copy those files to :

  • 04022022.asc
  • 04032022.asc
  • 04042022.asc

I create the array with the command Get-ChilItem but the copy-item only copied the first file 11022021.asc and the scripts is:

$filename = Get-ChildItem '/home' | where{ $_.Extension -like "*.asc" }
foreach ($a in $filename) {
Write-Host "Copy $a"
Copy-Item -Force "$a" ("/home/{0:MMddyyyy}.asc" -f ((get-date).AddMonths(5)))

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,627 questions
No comments
{count} votes

2 answers

Sort by: Most helpful
  1. DaveK 1,736 Reputation points
    Get-ChildItem '/home' -Filter *.asc |
        foreach {Copy-Item -Force -Path $_.FullName -Destination ("/home/" + [datetime]::parseexact($_.BaseName, 'MMddyyyy', $null).AddMonths(5).ToString('MMddyyyy') + $_.Extension)}

    I got this to work outputting the new files but with the filename date incremented by 5 months.

  2. Rich Matheisen 35,191 Reputation points

    I'd expand a bit on @DaveK proposal (I'd vote for it, too -- but it's been posted as a comment and not as an answer):

    Get-ChildItem '/home' -Filter *.asc |  
        ForEach-Object {  
            $f = $_.FullName        # save in case of exception  
                $d = [datetime]::parseexact($_.BaseName, 'MMddyyyy', $null).AddMonths(5).ToString('MMddyyyy')  
                $s = "{0}{1}.{2}" -f '/home/', $d, $_.Extension  
                Copy-Item -Path $_.FullName -Destination $s -ErrorAction STOP  
                "Failed to copy file '$f' to '$s' :`r`n$_"  
    No comments