SQL Server Last modification Date file system by creating a script

mfuanj7w  于 2024-01-05  发布在  其他
关注(0)|答案(2)|浏览(152)

I need to create an script or query to give me the last modification date of a file system. I have the below query and it works perfectly for an overwitted backup file. but I need to run it for *.bak that shows me the latest backup file modification date during many backup files:

--

  1. if exists(select 1 from tempdb..sysobjects where name='##tmp')
  2. drop table ##tmp
  3. create table ##tmp(mdate varchar(8000))
  4. insert ##tmp
  5. exec master.dbo.xp_cmdshell 'dir g:\SQL_Backup\filename.bak' -- (I need the --last backup file name which the name keep changing every week)
  6. set rowcount 5
  7. delete from ##tmp
  8. set rowcount 0
  9. select top(1) substring(mdate,1,20) as 'Last modified date' from ##tmp
tnkciper

tnkciper1#

I've never worked with these views, so this really need a reality check before you really integrate it, but this may help:

  1. select
  2. top 1 backupSetName = bs.name,
  3. backupFilePath = bf.physical_name,
  4. backupFileLogicalName = bf.logical_name,
  5. bs.backup_start_date,
  6. bs.backup_finish_date
  7. from msdb.dbo.backupfile bf
  8. join msdb.dbo.backupSet bs on bf.backup_set_id = bs.backup_set_id
  9. where right(bf.physical_name,4) = '.mdf'
  10. order by backup_finish_date desc;

"Backup Set" records the actual dates. Since it is one-to-many with "Backup Files", it means that the '.mdf' and '.ldf' file dates are recorded together. I just excluded the latter in the above output.

t9eec4r0

t9eec4r02#

I can run the PowerShell script and store in in sql server job. It ran successfully.

  1. $source = "\\00.0.00.00\your file location"
  2. $filetype = "dif" (or "bak")
  3. Get-ChildItem "$source\*" -Include "*.$filetype" | sort LastWriteTime | select -last 1
  4. $datetime=[datetime]::Today
  5. if($datetime.DayOfWeek -match 'Monday'){
  6. Write-Host "YES"
  7. }elseif($datetime.DayOfWeek -match 'Tuesday|Thursday|Saturday'){
  8. Write-Host "NO"
  9. }else{
  10. Write-Host "YES"
  11. }
展开查看全部

相关问题