PowerShell脚本,用于查找最新文件并检查其大小

时间:2014-07-21 14:09:58

标签: powershell filesystems

我有一个简单的PowerShell脚本来查找目录中的最新文件,但是我无法检查文件大小是否大于0 MB。我在下面发布了我的脚本:

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

请告诉我如何解决这个问题。

2 个答案:

答案 0 :(得分: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' }

答案 1 :(得分: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 "backup_openerp@zxc.com" -To "admins@zxc.com" -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 "backup_openerp@zxc.com" -To "admins@zxc.com" -Subject "OpenERP database backup for PROD has been failed !" -Body "Failed ! Backup of the database OpenERP is empty:    $mail" -SmtpServer "XXX.XXX.XXX.XXX"
}