简体   繁体   中英

PowerShell script to find the latest file and check its size

I have a simple PowerShell script to find the latest file in a directory, but I having trouble checking if the file size is larger than 0 MB. I have posted my script below:

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

Please give me some advice on what I can do to fix this.

You're using PowerShell very, very, very wrongly here. As in, it actually hurts (both you and me, I guess ;-)).

A more natural way would be to use the pipeline to find the latest file:

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

then you still have a FileInfo object here, which has all relevant properties:

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

I do it something like's that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM