简体   繁体   中英

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, ie 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

If you use $month = Get-Date -Format "MM" this will get you the month as a number. If I understand what you are trying to achive this should match you source path.

$Date = get-date
$Path = "F:\BB\" + "$($Date.year)" + "\" + "$($Date.month)" + "\"
Copy-Item -Path $Path -Destination F:\BB

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM