我遇到了一些我编写的脚本的问题 - 我试图让脚本的这一部分循环遍历并查找创建日期大于上次运行备份的任何文件。
$auditDate = (Get-Date).AddDays(0)
$lastAudit = Get-Content $auditLog | Select-Object -last 1
$desDir = "E:\Backup\"
$srcDir = "C:\\Data"
foreach ($file in Get-ChildItem $srcDir)
{
if ($file.CreationTime.Date.toString("dd/MM/yyyy") -gt $lastAudit)
{
Copy-Item $file.FullName $desDir
}
{
}
}
在我运行脚本的那一刻,我将文件夹中的所有文件都复制过来。
有什么想法吗?
答案 0 :(得分:3)
部分问题可能是将日期比较为字符串。例如:
#April 12,2011 is greater than July 7, 2014
"12/04/2011" -gt "07/07/2014"
True
#July 7, 2014 is not greater than June 8, 2014
"07/07/2014" -gt "08/06/2014"
False
看看这是否有帮助
#Not used in your example but why add 0 days to now?
$auditDate = [DateTime]::Now
$lastAudit = Get-Content $auditLog | Select-Object -last 1
$desDir = "E:\Backup\"
$srcDir = "C:\Data"
#Create a datetime object
$lastAuditDate = [DateTime]::Now
#Parse the retrieved timestamp to a datetime object
#note there is an overload for this method if you need to specify culture
if([DateTime]::TryParse($lastAudit,[ref]$lastAuditDate)){
#Date parsed successfully get all files newer than the parsed date and copy them
#To exclude directories add a -File to Get-ChildItem
#To recurse through subdirectories add a -Recurse
Get-ChildItem $srcdir | Where-Object {$_.CreationTime.Date -gt $lastAuditDate} | ForEach-Object {Copy-Item $_.FullName $desDir}
}else{
Write-Error "Failed to parse retrieved date"
}
请注意,如果此目录很大,则使用带有嵌套if语句的foreach-object可能比where-object更快。