Powershell Script to copy files based on date modifed to check newest file from a remote location

空扰寡人 提交于 2019-12-04 03:49:49

问题


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!

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
    }

}

回答1:


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.

$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".



回答2:


It has been a while since I did anything in PowerShell. However you may want to try to Echo out the values you are comparing to see what they are really returning.

Echo "LastWrite : " & $file.LastWriteTime

Echo "Copy After : " & ($Curr_date).adddays($Max_days)

This would help to determine what you are attempting to compare. HopeThisHelps at least a little.



来源:https://stackoverflow.com/questions/29421519/powershell-script-to-copy-files-based-on-date-modifed-to-check-newest-file-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!