PowerShell: 找到一个目录下最新的文件

需求: sql server数据库每天备份到一个目录中, 文件名的Pattern是Discovery20120919.bak和Discovery20120919_log.bak 分别是数据库的Full backup和Log backup. 写一个脚本取得一个目录下最新的文件,并且文件名中包含Discovery但是却不包含log.

 

function FindLatestBackupFile([String]$backupPath, [String]$BackupFilePattern, [String]$ExcludeFilePattern)
{

    $LastBackup = dir $backupPath | Where-Object {!$_.PSIsContainer} | Where-Object {$_.name -like "*" +$BackupFilePattern+ "*.bak"} | Where-Object{ $_.name -notlike "*" + $ExcludeFilePattern+ "*.bak" }|  Sort-Object {$_.LastWriteTime} -Descending | Select-Object -First 1
    $LatestBackupFilePath = $LastBackup.FullName
    return $LatestBackupFilePath
}



$backupPath = "E:\temp"
$BackupFilePattern = "Discovery"
$ExcludeFilePattern = "log"

FindLatestBackupFile $backupFile  $BackupFilePattern  $ErrorView

基本思路就是用 Where-Object 进行过滤,用Sort-Object进行排序,Select-Object进行选择。

posted @ 2012-09-24 09:33  蔡秋心  阅读(1199)  评论(0编辑  收藏  举报