Question:
I am new to powershell scripting and i cant figure out why my script copies
all files and doesn’t seem to check the date and then copies all the files
anyway. I was trying to do by days and minutes too, but I am not quite sure
on how to do that. any help would be great!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
see my script below. $RemotePath = "\\eb-pc\E$\testlocation\*.txt" $LocalPath = "C:\testlocation" $Max_days = "-1" #Max_mins = "-5" $Curr_date = get-date #Checking date and then copying file from RemotePath to LocalPath Foreach($file in (Get-ChildItem $RemotePath)) { if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days)) { Copy-Item -Path $file.fullname -Destination $LocalPath #Move-Item -Path $file.fullname -Destination $LocalPath } } |
Answer:
If you want to use Hours and minutes, instead of AddDays, just use the .AddMinutes(), .AddHours(), or .AddSeconds() methods instead.
For what it’s worth, I made a small modifcation, adding an Else{Scriptblock} to the script to echo out the files which aren’t being copied. As written your code will only copy files written in the last 24 hours.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
$RemotePath = "t:\" $LocalPath = "C:\temp" $Max_days = "-1" #Max_mins = "-5" $Curr_date = get-date #Checking date and then copying file from RemotePath to LocalPath Foreach($file in (Get-ChildItem $RemotePath)) { if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days)) { Copy-Item -Path $file.fullname -Destination $LocalPath -WhatIf #Move-Item -Path $file.fullname -Destination $LocalPath } ELSE {"not copying $file" } } >What if: Performing the operation "Copy File" on target "Item: T:\file.htm Destination: C:\temp\file.ht m". not copying ListOfSacredVMs.txt not copying newUser_01.png not copying newUser_015.png not copying newUser_02.png not copying newUser_03.png What if: Performing the operation "Copy File" on target "Item: T:\values.csv Destination: C:\temp\values.csv". |