Search code examples
powershellif-statementfile-copying

copying files from daily folders using Powershell


I am looking to move daily created files each day to another folder. These files are saved to the relevant YYYY\MM\folder each day. Now I have created a way to move these files over using the year/month date function, however because there a number attached to the month, i.e. December looks like "12. December" it becomes a little tricky.

I tried to amend this with an If statement which would assign "a" to the relevant number corresponding with the month however it doesnt work.

$year = (Get-Date).Year
$month = Get-Date -Format "MMMMMMMM"
$day = (Get-Date).Day

$a = ""



If ($month = "January") { $a = "1."}
Elseif ($month = "February") { $a = "2."}
Elseif ($month = "March") { $a = "3."}
Elseif ($month = "April") { $a = "4."}
Elseif ($month = "May") { $a = "5."}
Elseif ($month = "June") { $a = "6."}
Elseif ($month = "July") { $a = "7."}
Elseif ($month = "August") { $a = "8."}
Elseif ($month = "September") { $a = "9."}
Elseif ($month = "October") { $a = "10."}
Elseif ($month = "November") { $a = "11."}
Elseif ($month = "December") { $a = "12."}



$month = Get-Date -Format $a" MMMMMMMM"


Copy-Item -Path F:\BB\$year\$month\Scan.pdf  -Destination F:\BB

Any idea how to fix this/where am i going wrong. This is my first time writing in Powershell.

Edit: I am getting an error in the file location it is copying to does not register the difference in the coressponding months. For example the if statement states that if the month is = December a should = 12. but its currently coming up as 1. which should be the case for if it were January


Solution

  • The different forms of the month may as well be repeated in the format string, where

    M    = month number without leading zeroes
    MM   = month number with    leading zeroes
    MMM  = abbreviated month name 
    MMMM = full month name
    

    So:

    $Month = Get-Date -f "M. MMMM"
    

    > $Month
    12. December
    

    As the format string can contain any letter you can build the source path in one step:
    (escaped with a backslash if interfering with a format letter)

    $Source = "F:\BB\{0:yyyy\\M. MMMM}\Scan.pdf" -f (Get-Date)
    

    > $Source
    F:\BB\2018\12. Dezember\Scan.pdf
    

    But I'm missing the days here?