2023

This blog post will break down the provided PowerShell code, explaining how it works to retrieve Windows Server reboot history. We'll also discuss how to interpret the results and potential enhancements.

Understanding the Code
What does the code do?

  • Retrieves system event log entries related to system restarts (Event ID 1074).
  • Filters events based on a specified date range (last 30 days by default).
  • Extracts relevant information (time, message, reason, user) from the events.
  • Exports the results to a CSV file for easy analysis.
  • Breakdown of the code:


Get-WinEvent -FilterHashtable @{
    logname='System'
    id=1074
    StartTime=(Get-Date).AddDays(-30)  # Adjust as needed
} -MaxEvents 1000 |  # Increase if needed
Select-Object TimeCreated, 
    @{Name='Message';Expression={$_.Message.Trim()}},
    @{Name='Reason';Expression={$_.Properties[2].Value}},
    @{Name='User';Expression={$_.Properties[6].Value}} | 
Export-Csv -Path C:\Results\windowsrestart.csv -NoTypeInformation

Get-WinEvent: Retrieves events from the system event log.
  • -FilterHashtable: Specifies filter criteria.
  • logname='System': Looks in the System event log.
  • id=1074: Filters for events with ID 1074 (system restarts).
  • StartTime=(Get-Date).AddDays(-30): Sets the start time to 30 days ago. Adjust as needed.
  • -MaxEvents 1000: Limits results to 1000 events. Increase if needed.

Select-Object: Selects and renames properties for output.
  • TimeCreated: Keeps the original time created property.
  • Message: Extracts and trims the event message.
  • Reason: Extracts the reason for the restart from the event properties.
  • User: Extracts the user associated with the restart from the event properties.
  • Export-Csv: Exports the results to a CSV file named windowsrestart.csv.


This blog post will break down the provided PowerShell code, Understanding when and why your server rebooted is crucial for troubleshooting performance issues, security incidents, and overall system health. PowerShell, a powerful scripting language, provides a convenient way to extract this information from the Windows Event Log. This blog post will dissect the following PowerShell command and explain how it can be used to uncover your server’s reboot history:

[code type="SQL"] Get-WinEvent -FilterHashtable @{ LogName = 'System' Id = @(6005, 6006, 1074) StartTime = (Get-Date).AddDays(-60) # Last 60 days EndTime = Get-Date } -MaxEvents 50 | # Recent 50 messages Select-Object TimeCreated, Id, Message[/code]

Here are the results looks like: 


Understanding the Results:
Executing this command will output a list of events related to system shutdowns and restarts within the last 60 days. Each entry will display the event time, event ID, and a brief description of the event.

 Here’s a fantastic PowerShell script that can simplify our daily tasks by helping us search for events in the Windows Event Viewer. To use this script, open PowerShell ISE and run it. The output will be generated in the specified location. In this example, we’ve chosen the C:\Results folder, but feel free to customize it according to your requirements. You can also add or remove event IDs as needed. The script will create a CSV file that we can review

Code shown as follows:

[code type="SQL"] $ErrorActionPreference = "Continue" $startDate = (Get-Date).AddDays(-30) # Adjust as needed $endDate = Get-Date $filterHash = @{ LogName = @('System', 'Application') ID = @(7036, 17162, 17163, 17165) StartTime = $startDate EndTime = $endDate } try { $events = Get-WinEvent -FilterHashtable $filterHash -ErrorAction Stop } catch { Write-Warning "Error retrieving events: $_" $events = @() } if ($events.Count -gt 0) { $results = $events | ForEach-Object { $eventMessage = $_.Message.Trim() $sqlRelated = $eventMessage -match '(MSSQLSERVER|SQL Server \(|SQL Server Agent)' if ($sqlRelated -or $_.Id -in @(17162, 17163, 17165)) { [PSCustomObject]@{ TimeCreated = $_.TimeCreated EventID = $_.Id LogName = $_.LogName Message = $eventMessage Level = $_.LevelDisplayName ServerName = $_.MachineName Service = if ($_.Id -eq 7036) { if ($eventMessage -match 'The (.*) service') { $matches[1] } else { "Unknown Service" } } elseif ($_.ProviderName -eq 'MSSQLSERVER') { "SQL Server" } else { "SQL Related Service" } State = if ($_.Id -eq 7036) { if ($eventMessage -match 'entered the (.*) state') { $matches[1] } else { "Unknown State" } } else { switch ($_.Id) { 17162 { "Started" } 17163 { "Stopped" } 17165 { "Terminating" } default { "State Change" } } } UserName = $_.UserId } } } $exportPath = "C:\Results\SQLServerCombinedEvents.csv" $results | Where-Object { $_ -ne $null } | Sort-Object TimeCreated -Descending | Export-Csv -Path $exportPath -NoTypeInformation Write-Host "SQL Server events exported to $exportPath" } else { Write-Warning "No events found matching the specified criteria." } [/code]


Above PowerShell code will get generated output file in the C:\Results folder








$ErrorActionPreference = "Continue"

$startDate = (Get-Date).AddDays(-30)  # Adjust as needed
$endDate = Get-Date

$filterHash = @{
    LogName = @('System', 'Application')
    ID = @(7036, 17162, 17163, 17165)
    StartTime = $startDate
    EndTime = $endDate
}

try {
    $events = Get-WinEvent -FilterHashtable $filterHash -ErrorAction Stop
}
catch {
    Write-Warning "Error retrieving events: $_"
    $events = @()
}

if ($events.Count -gt 0) {
    $results = $events | ForEach-Object {
        $eventMessage = $_.Message.Trim()
        $sqlRelated = $eventMessage -match '(MSSQLSERVER|SQL Server \(|SQL Server Agent)'
        
        if ($sqlRelated -or $_.Id -in @(17162, 17163, 17165)) {
            [PSCustomObject]@{
                TimeCreated = $_.TimeCreated
                EventID = $_.Id
                LogName = $_.LogName
                Message = $eventMessage
                Level = $_.LevelDisplayName
                ServerName = $_.MachineName
                Service = if ($_.Id -eq 7036) {
                    if ($eventMessage -match 'The (.*) service') { $matches[1] }
                    else { "Unknown Service" }
                } elseif ($_.ProviderName -eq 'MSSQLSERVER') {
                    "SQL Server"
                } else {
                    "SQL Related Service"
                }
                State = if ($_.Id -eq 7036) {
                    if ($eventMessage -match 'entered the (.*) state') { $matches[1] }
                    else { "Unknown State" }
                } else { 
                    switch ($_.Id) {
                        17162 { "Started" }
                        17163 { "Stopped" }
                        17165 { "Terminating" }
                        default { "State Change" }
                    }
                }
                UserName = $_.UserId
            }
        }
    }

    $exportPath = "C:\Results\SQLServerCombinedEvents.csv"
    $results | 
        Where-Object { $_ -ne $null } |
        Sort-Object TimeCreated -Descending | 
        Export-Csv -Path $exportPath -NoTypeInformation

    Write-Host "SQL Server events exported to $exportPath"
}
else {
    Write-Warning "No events found matching the specified criteria."
}

We are done.

Here is another good PowerShell script that can make a SQL Admin’s life easier. This script can be used to check the health of SQL servers and retrieve information about them. The collected data will be saved in both CSV and HTML formats. Additionally, an error log file is generated, allowing you to manually review any failed servers.

To implement this, follow these steps:

  1. Create a folder named “CommandTree” in the C:\ drive of the server.
  2. Place the “ServerList.txt” and “TsqlCommand.sql” files in the CommandTree folder.
  3. The PowerShell script will connect to each server listed in the ServerList.txt file and execute the T-SQL command provided in the TsqlCommand.sql file.
  4. The output files (CSV and HTML formats) will be generated in the same location. 

[code type="SQL"] # Define paths on WINSRVR1 $basePath = "C:\commandTree" $sqlCommandPath = "$basePath\tsqlcommand.sql" $serverListPath = "$basePath\serverlist.txt" $logPath = "$basePath\connectionlog.txt" # Renamed from errorLogPath to logPath $consolidatedCsvPath = "$basePath\consolidated_results.csv" $consolidatedHtmlPath = "$basePath\consolidated_results.html" # Function to log messages function Write-Log { param ( [string]$Message, [string]$Status ) $logMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $Status - $Message" Add-Content -Path $logPath -Value $logMessage if ($Status -eq "Error") { Write-Host $logMessage -ForegroundColor Red } else { Write-Host $logMessage -ForegroundColor Green } } # Function to connect, execute query, and return results function Get-SqlQueryResults { param( [string] $ServerInstance ) try { # Read SQL command $sql = Get-Content $sqlCommandPath -Raw # Execute query and capture results $results = Invoke-Sqlcmd -ServerInstance $ServerInstance -Query $sql # Add a column for the server name $results | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $ServerInstance -Force Write-Log -Message "Successfully processed $ServerInstance" -Status "Success" return $results } catch { $errorMessage = $_.Exception.Message Write-Log -Message "Error processing $($ServerInstance): $errorMessage" -Status "Error" return $null } } # Main script execution try { # Check if required files exist if (-not (Test-Path $sqlCommandPath) -or -not (Test-Path $serverListPath)) { throw "Required files not found. Please ensure tsqlcommand.sql and serverlist.txt exist in $basePath" } # Read server list $servers = Get-Content $serverListPath # Initialize an array to store all results $allResults = @() # Process each server foreach ($server in $servers) { Write-Host "Processing $server..." -ForegroundColor Cyan $serverResults = Get-SqlQueryResults -ServerInstance $server if ($serverResults) { $allResults += $serverResults } } # Save consolidated results to CSV if ($allResults.Count -gt 0) { $allResults | Select-Object -Property * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors | Export-Csv -NoTypeInformation -Path $consolidatedCsvPath Write-Log -Message "Consolidated CSV results saved to $consolidatedCsvPath" -Status "Success" # Generate consolidated HTML report $htmlHeader = @"

Consolidated Results for All Servers

"@ $htmlFooter = "" $htmlBody = $allResults | Select-Object -Property * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors | ConvertTo-Html -Fragment $htmlHeader + $htmlBody + $htmlFooter | Out-File -FilePath $consolidatedHtmlPath -Encoding UTF8 Write-Log -Message "Consolidated HTML results saved to $consolidatedHtmlPath" -Status "Success" } else { Write-Log -Message "No results to save." -Status "Warning" } Write-Log -Message "Script completed. Consolidated results saved to CSV and HTML files in $basePath on WINSRVR1." -Status "Success" } catch { Write-Log -Message "An error occurred: $_" -Status "Error" } [/code]
Results shown as below in the server. 



If the above code is not copied / not worked you can use below one.

# Define paths on WINSRVR1
$basePath = "C:\commandTree"
$sqlCommandPath = "$basePath\tsqlcommand.sql"
$serverListPath = "$basePath\serverlist.txt"
$logPath = "$basePath\connectionlog.txt"  # Renamed from errorLogPath to logPath
$consolidatedCsvPath = "$basePath\consolidated_results.csv"
$consolidatedHtmlPath = "$basePath\consolidated_results.html"

# Function to log messages
function Write-Log {
    param (
        [string]$Message,
        [string]$Status
    )
    $logMessage = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - $Status - $Message"
    Add-Content -Path $logPath -Value $logMessage
    if ($Status -eq "Error") {
        Write-Host $logMessage -ForegroundColor Red
    } else {
        Write-Host $logMessage -ForegroundColor Green
    }
}

# Function to connect, execute query, and return results
function Get-SqlQueryResults {
    param(
        [string] $ServerInstance
    )
    try {
        # Read SQL command
        $sql = Get-Content $sqlCommandPath -Raw
        
        # Execute query and capture results
        $results = Invoke-Sqlcmd -ServerInstance $ServerInstance -Query $sql
        
        # Add a column for the server name
        $results | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $ServerInstance -Force
        
        Write-Log -Message "Successfully processed $ServerInstance" -Status "Success"
        return $results
    }
    catch {
        $errorMessage = $_.Exception.Message
        Write-Log -Message "Error processing $($ServerInstance): $errorMessage" -Status "Error"
        return $null
    }
}

# Main script execution
try {
    # Check if required files exist
    if (-not (Test-Path $sqlCommandPath) -or -not (Test-Path $serverListPath)) {
        throw "Required files not found. Please ensure tsqlcommand.sql and serverlist.txt exist in $basePath"
    }

    # Read server list
    $servers = Get-Content $serverListPath

    # Initialize an array to store all results
    $allResults = @()

    # Process each server
    foreach ($server in $servers) {
        Write-Host "Processing $server..." -ForegroundColor Cyan
        $serverResults = Get-SqlQueryResults -ServerInstance $server
        if ($serverResults) {
            $allResults += $serverResults
        }
    }

    # Save consolidated results to CSV
    if ($allResults.Count -gt 0) {
        $allResults | Select-Object -Property * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors | Export-Csv -NoTypeInformation -Path $consolidatedCsvPath
        Write-Log -Message "Consolidated CSV results saved to $consolidatedCsvPath" -Status "Success"

        # Generate consolidated HTML report
        $htmlHeader = @"
        <html>
        <head>
            <style>
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid black; padding: 8px; text-align: left; }
                th { background-color: #f2f2f2; }
            </style>
        </head>
        <body>
        <h2>Consolidated Results for All Servers</h2>
"@
        $htmlFooter = "</body></html>"
        $htmlBody = $allResults | Select-Object -Property * -ExcludeProperty RowError, RowState, Table, ItemArray, HasErrors | ConvertTo-Html -Fragment
        $htmlHeader + $htmlBody + $htmlFooter | Out-File -FilePath $consolidatedHtmlPath -Encoding UTF8
        Write-Log -Message "Consolidated HTML results saved to $consolidatedHtmlPath" -Status "Success"
    } else {
        Write-Log -Message "No results to save." -Status "Warning"
    }

    Write-Log -Message "Script completed. Consolidated results saved to CSV and HTML files in $basePath on WINSRVR1." -Status "Success"
}
catch {
    Write-Log -Message "An error occurred: $_" -Status "Error"
}

-- We are done.

what is this yar [full-post] [code type="CSS"]contenteditable="true" SELECT @@servername[Servername],getdate() [TimeNow],command, r.session_id, r.blocking_session_id,s.text, start_time, percent_complete, CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), ' + CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, ' + CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time, CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), ' + CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, ' + CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go, dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s WHERE r.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG','DBCC')[/code] Hello world
contenteditable="true">
[code type="sql"] 
SELECT @@servername[Servername],getdate() [TimeNow],command, r.session_id, r.blocking_session_id,s.text,
start_time,
percent_complete, 
CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), '
+ CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, '
+ CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time,
CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), '
+ CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, '
+ CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go,
dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time 
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG','DBCC')
[/code]


use master
go
BEGIN  SET nocount ON
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('tempdb..#DBFileInfo'))  BEGIN  DROP TABLE #dbfileinfo  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#LogSizeStats'))  BEGIN  DROP TABLE #logsizestats  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#DataFileStats'))  BEGIN  DROP TABLE #datafilestats  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#FixedDrives'))  BEGIN  DROP TABLE #fixeddrives  END
 CREATE TABLE #fixeddrives  (  DriveLetter VARCHAR(10),  MB_Free DEC(20, 2)  )
 CREATE TABLE #datafilestats  (  DBName VARCHAR(255),  DBId INT,  FileId TINYINT,  [FileGroup] TINYINT,  TotalExtents DEC(20, 2),  UsedExtents DEC(20, 2),  [Name] VARCHAR(255),  [FileName] VARCHAR(400)  )
 CREATE TABLE #logsizestats  (  DBName VARCHAR(255) NOT NULL PRIMARY KEY CLUSTERED,  DBId INT,  LogFile REAL,  LogFileUsed REAL,  Status BIT  )
 CREATE TABLE #dbfileinfo  (  [ServerName] VARCHAR(255),  [DBName] VARCHAR(65),  [LogicalFileName] VARCHAR(400),  [UsageType] VARCHAR (30),  [Size_MB] DEC(20, 2),  [SpaceUsed_MB] DEC(20, 2),  [MaxSize_MB] DEC(20, 2),  [NextAllocation_MB] DEC(20, 2),  [GrowthType] VARCHAR(65),  [FileId] SMALLINT,  [GroupId] SMALLINT,  [PhysicalFileName] VARCHAR(400),  [DateChecked] DATETIME  )
 DECLARE @SQLString VARCHAR(3000)  DECLARE @MinId INT  DECLARE @MaxId INT  DECLARE @DBName VARCHAR(255)  DECLARE @tblDBName TABLE (  RowId INT IDENTITY(1, 1),  DBName VARCHAR(255),  DBId INT)
 INSERT INTO @tblDBName  (DBName,  DBId)  SELECT [Name],  DBId  FROM master..sysdatabases  WHERE ( Status & 512 ) = 0 /*NOT IN (536,528,540,2584,1536,512,4194841)*/  ORDER BY [Name]
 INSERT INTO #logsizestats  (DBName,  LogFile,  LogFileUsed,  Status)  EXEC ('DBCC sqlperf(logspace) WITH no_infomsgs')
 UPDATE #logsizestats  SET DBId = Db_id(DBName)
 INSERT INTO #fixeddrives  EXEC master..Xp_fixeddrives
 SELECT @MinId = Min(RowId),  @MaxId = Max(RowId)  FROM @tblDBName
 WHILE ( @MinId <= @MaxId )  BEGIN  SELECT @DBName = [DBName]  FROM @tblDBName  WHERE RowId = @MinId
 SELECT @SQLString = 'SELECT ServerName = @@SERVERNAME,' +  ' DBName = ''' +  @DBName +  ''',' +  ' LogicalFileName = [name],' + ' UsageType = CASE WHEN (64&[status])=64 THEN ''Log'' ELSE ''Data'' END,' +  ' Size_MB = [size]*8/1024.00,' +  ' SpaceUsed_MB = NULL,' + ' MaxSize_MB = CASE [maxsize] WHEN -1 THEN -1 WHEN 0 THEN [size]*8/1024.00 ELSE maxsize/1024.00*8 END,'+ ' NextExtent_MB = CASE WHEN (1048576&[status])=1048576 THEN ([growth]/100.00)*([size]*8/1024.00) WHEN [growth]=0 THEN 0 ELSE [growth]*8/1024.00 END,'+ ' GrowthType = CASE WHEN (1048576&[status])=1048576 THEN ''%'' ELSE ''Pages'' END,'+ ' FileId = [fileid],' + ' GroupId = [groupid],' +  ' PhysicalFileName= [filename],' +  ' CurTimeStamp = GETDATE()' + 'FROM [' + @DBName +  ']..sysfiles'
 PRINT @SQLString
 INSERT INTO #dbfileinfo  EXEC (@SQLString)
 UPDATE #dbfileinfo  SET SpaceUsed_MB = Size_MB / 100.0 * (SELECT LogFileUsed  FROM #logsizestats  WHERE DBName = @DBName)  WHERE UsageType = 'Log'  AND DBName = @DBName
 SELECT @SQLString = 'USE [' + @DBName +  '] DBCC SHOWFILESTATS WITH NO_INFOMSGS'
 INSERT #datafilestats  (FileId,  [FileGroup],  TotalExtents,  UsedExtents,  [Name],  [FileName])  EXECUTE(@SQLString)
 UPDATE #dbfileinfo  SET [SpaceUsed_MB] = S.[UsedExtents] * 64 / 1024.00  FROM #dbfileinfo AS F  INNER JOIN #datafilestats AS S  ON F.[FileId] = S.[FileId]  AND F.[GroupId] = S.[FileGroup]  AND F.[DBName] = @DBName
 TRUNCATE TABLE #datafilestats
 SELECT @MinId = @MinId + 1 END
 SELECT [ServerName],  [DBName],  [LogicalFileName],  [UsageType]  AS SegmentName,  B.MB_Free  AS FreeSpaceInDrive,  [Size_MB],  [SpaceUsed_MB],  [Size_MB] - [SpaceUsed_MB]  AS FreeSpace_MB,  Cast(( [Size_MB] - [SpaceUsed_MB] ) / [Size_MB] AS DECIMAL(4, 2))  AS  FreeSpace_Pct,  [MaxSize_MB],  [NextAllocation_MB],  ( [Size_MB] - [SpaceUsed_MB] ) - ( [NextAllocation_MB] )  AS alert_switch,  ( B.MB_Free ) + ( ( [Size_MB] - [SpaceUsed_MB] ) -  ( [NextAllocation_MB] ) ) AS  will_be_on_drive,  CASE MaxSize_MB  WHEN -1 THEN Cast(Cast(( [NextAllocation_MB] / [Size_MB] ) * 100 AS INT  ) AS  VARCHAR(10)) +  ' %'  ELSE 'Pages'  END  AS [GrowthType],  [FileId],  [GroupId],  [PhysicalFileName],  CONVERT(SYSNAME, Databasepropertyex([DBName], 'Status'))  AS Status,  CONVERT(SYSNAME, Databasepropertyex([DBName], 'Updateability'))  AS Updateability,  CONVERT(SYSNAME, Databasepropertyex([DBName], 'Recovery'))  AS RecoveryMode,  CONVERT(SYSNAME, Databasepropertyex([DBName], 'UserAccess'))  AS UserAccess,  CONVERT(SYSNAME, Databasepropertyex([DBName], 'Version'))  AS Version,  [DateChecked]  FROM #dbfileinfo AS A  LEFT JOIN #fixeddrives AS B  ON Substring(A.PhysicalFileName, 1, 1) = B.DriveLetter  ORDER BY ( [Size_MB] - [SpaceUsed_MB] ) - ( [NextAllocation_MB] )
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#DBFileInfo'))  BEGIN  DROP TABLE #dbfileinfo  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#LogSizeStats'))  BEGIN  DROP TABLE #logsizestats  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#DataFileStats'))  BEGIN  DROP TABLE #datafilestats  END
 IF EXISTS (SELECT 1  FROM tempdb..sysobjects  WHERE [Id] = Object_id('Tempdb..#FixedDrives'))  BEGIN  DROP TABLE #fixeddrives  END
 SET nocount OFF END

 Hello this is the code test 


we are now adding tsql code test here [code type="CSS"]SELECT @@servername[Servername],getdate() [TimeNow],command, r.session_id, r.blocking_session_id,s.text, start_time, percent_complete, CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), ' + CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, ' + CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time, CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), ' + CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, ' + CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go, dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s WHERE r.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG','DBCC')[/code] Code content Editable content enabled cursor movement

SELECT @@servername[Servername],getdate() [TimeNow],command, r.session_id, r.blocking_session_id,s.text,
start_time,
percent_complete, 
CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), '
+ CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, '
+ CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time,
CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), '
+ CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, '
+ CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go,
dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time 
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG','DBCC')

SELECT @@servername[Servername],getdate() [TimeNow],command, r.session_id, r.blocking_session_id,s.text,
start_time,
percent_complete, 
CAST(((DATEDIFF(s,start_time,GetDate()))/3600) as varchar) + ' hour(s), '
+ CAST((DATEDIFF(s,start_time,GetDate())%3600)/60 as varchar) + 'min, '
+ CAST((DATEDIFF(s,start_time,GetDate())%60) as varchar) + ' sec' as running_time,
CAST((estimated_completion_time/3600000) as varchar) + ' hour(s), '
+ CAST((estimated_completion_time %3600000)/60000 as varchar) + 'min, '
+ CAST((estimated_completion_time %60000)/1000 as varchar) + ' sec' as est_time_to_go,
dateadd(second,estimated_completion_time/1000, getdate()) as est_completion_time 
FROM sys.dm_exec_requests r
CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) s
WHERE r.command in ('RESTORE DATABASE', 'BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG','DBCC')

Author Name

Contact Form

Name

Email *

Message *

Powered by Blogger.