locked
Powershell Script to append date to pdf's and move all pdf's to another folder RRS feed

  • Question

  • I have a script to append the date and move one file to another folder on the network. This script will be a task that runs nightly. How do I revise that to append today's date and move all pdf's to a folder on the network?

    $date = Get-Date -uFormat "%Y%m%d" ## These will become parameters in our function later $locationPath = "c:\myfiles\" $fileName = "test" $extension = ".txt" --probably "*.pdf" $old = $locationPath + $fileName + $extension $new = $locationPath + $fileName + "_" + $date + $extension
    $archiveFolder= $locationPath + "t:\myfiles\Archive\"

    Function RenameMoveFile($locationPath, $fileName, $extension, $archiveFolder)
    {
        $date = Get-Date -uFormat "%Y%m%d"
        $old = $locationPath + $fileName + $extension
        $new = $locationPath + $fileName + "_" + $date + $extension
        $archiveFolder = $locationPath + $archiveFolder + "\"
        Rename-Item $old $new
        Move-Item $new $archiveFolder
    }
    ## Call function
    RenameMoveFile -locationPath "C:\files\" -fileName "test" -extension ".txt" -archiveFolder "Archive"

    Thursday, January 9, 2020 4:34 PM

Answers

  • You can also generalize this like this:

    $archiveFolder = 't:\myfiles\Archive'
    Get-ChildItem *.pdf -File |
        ForEach-Object{
            $newname = '{0}_{1:yyyyMMdd}{2}' -f $_.BaseName,[datetime]::Today, $_.Extension
            $newname = Join-Path $archiveFolder $newname
            $_ | Move-Item -Destination $newname -WhatIf
        }
    


    \_(ツ)_/

    Thursday, January 9, 2020 5:50 PM

All replies

  • You can do both in the Move command. REname is just a variation on move.

    Just enumerate the files and call the function with each file.

    Simplify this by eliminating the function and just move all files in a loop with the new name as the target.


    \_(ツ)_/

    Thursday, January 9, 2020 5:35 PM
  • This is all you have to do to move and rename a file in one step:

    Get-ChildItem *.pdf -File |
        ForEach-Object{
            $newname = 't:\myfiles\Archive\{0}_{1:yyyyMMdd}{2}' -f $_.BaseName,[datetime]::Today, $_.Extension
            $_ | Move-Item -Destination $newname
        }


    \_(ツ)_/


    • Edited by jrv Thursday, January 9, 2020 5:45 PM
    • Proposed as answer by Peter Ziganki Friday, January 10, 2020 11:06 AM
    Thursday, January 9, 2020 5:44 PM
  • You can also generalize this like this:

    $archiveFolder = 't:\myfiles\Archive'
    Get-ChildItem *.pdf -File |
        ForEach-Object{
            $newname = '{0}_{1:yyyyMMdd}{2}' -f $_.BaseName,[datetime]::Today, $_.Extension
            $newname = Join-Path $archiveFolder $newname
            $_ | Move-Item -Destination $newname -WhatIf
        }
    


    \_(ツ)_/

    Thursday, January 9, 2020 5:50 PM