Append MMYYYY to File to Copy

  • $source="c:\fileloading" #location of starting directory
    $destination="c:\filecopy"; #location where files will be copied to
    $files=@("*dys_ihhist*")

    Get-ChildItem -recurse ($source) -include ($files) | Copy-Item -Destination ($destination + ($file.BaseName + "_" + (Get-Date -Format "MMyyyy") + $file.Extension ))

    I ran this no error, but didn't do anything

     

  • Jason A. Long wrote:

    I don't see where anyone has already said it, so I'll say it… “MMYYYY” is a date format to avoid. Using “YYYYMM” instead will allow you to actually sort those files chronologically.

    +1000 😉

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • OK, not as clean as you may like, but just saw this. Here's what I'd do:

    $source="c:\fileloading" #location of starting directory
    $destination="c:\filecopy"; #location where files will be copied to
    $files="*dys_ihhist*" #files matching this pattern

    # write a powershell command to get a list of files in $source matching the $files pattern
    $a = get-childitem $source -filter $files
    $a | foreach {write-host $($_.basename)-$(get-date -f yyyyMMdd)$($_.extension)}

    # write a powershell command to copy files from source to destination appending the date to the filename
    $a | foreach {copy-item $_.fullname $destination\$($_.basename)-$(get-date -f yyyyMMdd)$($_.extension)}

    I don't see the need for $files to do more than be a string and I find -filter works well here. Then I added a debug line for you wiht the foreach{write-host} to see the list of files with the extension. Basename is the name without the extension, which you are modifying to add the date stamp. I added dd, because I expect possible collissions with yyyymm, but I could be wrong. Up to you.

     

  • For giggles, this is from Copilot:

    2023-07-31 15_08_04-● copyfiles.ps1 - sqlsatwebsite - Visual Studio Code

  • Thanks worked nice.

  • Good to hear.

Viewing 6 posts - 16 through 20 (of 20 total)

You must be logged in to reply to this topic. Login to reply