2014-07-21 84 views
0

我有一個簡單的PowerShell腳本來查找目錄中的最新文件,但我無法檢查文件大小是否大於0 MB。我已經發布我的腳本如下:PowerShell腳本查找最新文件並檢查其大小

$olddate = [DateTime]::MaxValue 
$newdate = [DateTime]::MinValue 
$oldfn = "" 
$newfn = "" 
$path = "U:\PGCLUSTER_BACKUP" 
get-childitem $path | ForEach-Object { 
    if ($_.LastWriteTime -lt $olddate -and -not $_.PSIsContainer) { 
     $oldfn = $_.Name 
     $olddate = $_.LastWriteTime 
    } 
    if ($_.LastWriteTime -gt $newdate -and -not $_.PSIsContainer) { 
     $newfn = $_.Name 
     $newdate = $_.LastWriteTime 
    } 
} 

$output = "" 
if ($newfn -ne "") { $output += "`nNewest: " + $newdate + " -- " + $newfn } 

if ($output -eq "") { $output += "`nFolder is empty." } 
$output + "`n" 

請給我一些建議,我可以做些什麼來解決這個問題。

回答

3

您在這裏錯誤地使用了PowerShell,非常非常,。如在,它實際上傷害(你和我,我猜;-))。

更自然的方式是使用管道找到最新的文件:

$latest = Get-ChildItem $path | Sort LastWriteTime -Descending | select -First 1 

,那麼你仍然在這裏有一個FileInfo對象,它具有所有相關屬性:

if ($latest -and $latest.Length -gt 0) { 
    'Newest: {0:yyyy-MM-dd} -- {1}' -f $latest.LastWriteTime,$latest.Name 
} else { 'Folder is empty' } 
0

我做這樣的事情是這樣的:

$path = "F:\PGCLUSTER_BACKUP" 

$latest = Get-ChildItem $path | Sort LastWriteTime -Descending | select -First 1 
$mail='Newest file: {0:yyyy-MM-dd} -- {1}' -f $latest.LastWriteTime,$latest.Name 

if ($latest -and $latest.Length -gt 0) { 

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "OpenERP database backup for PROD has been successful !" -Body "Success! Backup of the database OpenERP is not empty: $mail" -SmtpServer "XXX.XXX.XXX.XXX" 
} else { 

Send-MailMessage -From "[email protected]" -To "[email protected]" -Subject "OpenERP database backup for PROD has been failed !" -Body "Failed ! Backup of the database OpenERP is empty: $mail" -SmtpServer "XXX.XXX.XXX.XXX" 
}