Way to find when system health file is rolling overHow are the system health extended events files rolling over?SSAS queries time out when Windows File System Cache dropsSystem Health Extented Event - Security_Ring_Buffer_Error_RecordedChance of skipping extended events when using an offset for the file targetRestoring Database when system can't find filepath specifiedThe system cannot find the file specifiedWhat does it means when you have “sql_exit_invoked” in System Health?How are the system health extended events files rolling over?File growth and location change for system health extended eventsIncorrect process utilization from System health extended events?When to Use Functions over Stored Procedures

Does this circuit have marginal voltage level problem?

What does "another" mean in this case?

List of Implementations for common OR problems

Phrasing "it says" or "it reads"

What could a Medieval society do with excess animal blood?

Magento 2: I am not aware about magneto optimization. Can you please share the steps for this?

Are there advantages in writing by hand over typing out a story?

What do you call the angle of the direction of an airplane?

What is -(-2,3,4)?

What do you call the motor that fuels the movement of a robotic arm?

Can the word "coexist" be used for more than two things/people/subjects/... etc?

How to compute the number of centroids for K-means clustering algorithm given minimal distance?

Who are the police in Hong Kong?

Show that there are infinitely more problems than we will ever be able to compute

Why would a propellor have blades of different lengths?

How can solar sailed ships be protected from space debris?

What is a "tittering order"?

Should I cheat if the majority does it?

gzip compress a local folder and extract it to remote server

How to widen the page

Why are symbols not written in words?

Phrase origin: "You ain't got to go home but you got to get out of here."

Does a reference have a storage location?

Why did moving the mouse cursor cause Windows 95 to run more quickly?



Way to find when system health file is rolling over


How are the system health extended events files rolling over?SSAS queries time out when Windows File System Cache dropsSystem Health Extented Event - Security_Ring_Buffer_Error_RecordedChance of skipping extended events when using an offset for the file targetRestoring Database when system can't find filepath specifiedThe system cannot find the file specifiedWhat does it means when you have “sql_exit_invoked” in System Health?How are the system health extended events files rolling over?File growth and location change for system health extended eventsIncorrect process utilization from System health extended events?When to Use Functions over Stored Procedures






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















Is there a way to find the events when system health extended event files are rolling over rather than manually monitoring for the events?



For my medium load server they stay upto 2-3 days. But for heavy loaded servers these files are rolling every 15 mins or so but no fixed pattern or timings. We know the reason why and working to filter out unwanted events or ones reported as issues.



I am curious if there is a way we can query at what time would the roll-over of files is happening. I do not see much documentation on MS docs as well but cant find this info?



Please suggest if its possible and how?










share|improve this question




























    4















    Is there a way to find the events when system health extended event files are rolling over rather than manually monitoring for the events?



    For my medium load server they stay upto 2-3 days. But for heavy loaded servers these files are rolling every 15 mins or so but no fixed pattern or timings. We know the reason why and working to filter out unwanted events or ones reported as issues.



    I am curious if there is a way we can query at what time would the roll-over of files is happening. I do not see much documentation on MS docs as well but cant find this info?



    Please suggest if its possible and how?










    share|improve this question
























      4












      4








      4








      Is there a way to find the events when system health extended event files are rolling over rather than manually monitoring for the events?



      For my medium load server they stay upto 2-3 days. But for heavy loaded servers these files are rolling every 15 mins or so but no fixed pattern or timings. We know the reason why and working to filter out unwanted events or ones reported as issues.



      I am curious if there is a way we can query at what time would the roll-over of files is happening. I do not see much documentation on MS docs as well but cant find this info?



      Please suggest if its possible and how?










      share|improve this question














      Is there a way to find the events when system health extended event files are rolling over rather than manually monitoring for the events?



      For my medium load server they stay upto 2-3 days. But for heavy loaded servers these files are rolling every 15 mins or so but no fixed pattern or timings. We know the reason why and working to filter out unwanted events or ones reported as issues.



      I am curious if there is a way we can query at what time would the roll-over of files is happening. I do not see much documentation on MS docs as well but cant find this info?



      Please suggest if its possible and how?







      sql-server sql-server-2016 extended-events






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 24 at 19:08









      BeginnerDBABeginnerDBA

      7871 gold badge7 silver badges21 bronze badges




      7871 gold badge7 silver badges21 bronze badges




















          2 Answers
          2






          active

          oldest

          votes


















          6














          You can get all the system_health event files and their oldest event like this:



          DECLARE @file_name AS nvarchar(max);
          DECLARE @file_path AS nvarchar(max);

          SELECT
          @file_name =
          CAST(st.target_data AS xml).value(
          N'(EventFileTarget/File/@name)[1]', N'nvarchar(max)')
          FROM sys.dm_xe_sessions s
          INNER JOIN sys.dm_xe_session_targets st
          ON s.[address] = st.event_session_address
          WHERE
          st.target_name = 'event_file'
          AND s.[name] = 'system_health';


          SELECT @file_path = LEFT(
          @file_name,
          LEN(@file_name) - CHARINDEX('', REVERSE(@file_name)) + 1);

          SELECT
          files.[file_name],
          MIN(CAST(files.event_data AS XML).value(N'(event/@timestamp)[1]', N'datetime')) AS oldest_event
          FROM sys.fn_xe_file_target_read_file
          (
          @file_path + 'system_health*',
          null, null, null
          ) files
          GROUP BY files.[file_name]
          OPTION(NO_PERFORMANCE_SPOOL, QUERYTRACEON 8649);


          Screenshot of SSMS results



          Note: for versions of SQL Server that don't support the NO_PERFORMANCE_SPOOL query hint (prior to SQL Server 2016), you can replace that with with QUERYTRACEON 8690 (see Spool operator and trace flag 8690 for details).



          The code above



          • gets the filename for the currently-active event file,

          • then attempts to extract the path using this method,

          • then uses the sys.fn_xe_file_target_read_file dynamic management function to get oldest event from each file

          Hat tip to Erik Darling for suggesting the query hints, which sped things up significantly in my tests



          So one way to accomplish your goal would be to run that query as a scheduled agent job, and log the results to a table. Then you'd be able to see when the "oldest event" changes for each file (AKA when the file rolls over).



          Recall that files can roll over for a number of different reasons.



          If performance is an issue, and you are comfortable with PowerShell, you are likely much better off using the approach offered by Dan Guzman here.






          share|improve this answer

























          • I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

            – BeginnerDBA
            Jun 26 at 18:21











          • @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

            – Josh Darnell
            Jun 26 at 18:26











          • Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

            – BeginnerDBA
            9 hours ago











          • @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

            – Josh Darnell
            4 hours ago


















          6














          Below is a powershell example that summarizes events by name from the local system_health target files using the new Microsoft [SqlServer.XEvent PowerShell module][1]. I've found it's much faster to process high event volumes using .NET/PowerShell than parsing XML in T-SQL. You can schedule this as a SQL Agent job to identify what is driving the event activity and take corrective action if needed.



          # Install the SqlServer.XEvent module from an admin PowerShell session before running this script:
          # Install-Module -Name SqlServer.XEvent

          # get list of system_health trace files
          Function Get-XeFiles()
          $connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          try

          $xe_files = Get-XeFiles
          foreach($xe_file in $xe_files)
          try Group-Object -Property Name -NoElement
          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw





          catch
          throw



          Sample output:



          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057213063750000.xel

          Count Name
          ----- ----
          860 sp_server_diagnostics_component_result
          1072 scheduler_monitor_system_health_ring_buffer_recorded
          2 connectivity_ring_buffer_recorded
          1 security_error_ring_buffer_recorded

          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057856050380000.xel

          Count Name
          ----- ----
          1312 sp_server_diagnostics_component_result
          1644 scheduler_monitor_system_health_ring_buffer_recorded
          28 scheduler_monitor_non_yielding_ring_buffer_recorded
          4 connectivity_ring_buffer_recorded
          2 error_reported
          2 wait_info
          6 security_error_ring_buffer_recorded


          EDIT:



          This can also be done remotely and against multiple servers with a single script as long as the trace folder is available remotely via a share. The example below runs against each server in a list and uses a UNC path to access the trace files. Because this version uses the drive letter admin share, it must run under a Windows account that has Windows admin permissions on the remote box. A less privileged account can be used if you create a share on each server and use that share name instead.



          # get list of system_health trace files with admin share UNC path
          Function Get-XeFiles($serverName)
          $connectionString = "Data Source=$serverName;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          # change driver letter to admin share UNC path (e.g. "D:" to "\servernamed$")
          $traceFileDirectory = "\$serverName$($traceFileDirectory.Replace(":", "$"))"
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          # specify list of servers here
          $serverList = @(
          "YourServer1"
          ,"YourServer2"
          ,"YourServer3"
          )

          try
          foreach($server in $serverList)

          $xe_files = Get-XeFiles -serverName $server
          foreach($xe_file in $xe_files)
          try Format-Table -AutoSize

          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw






          catch
          throw






          share|improve this answer

























          • Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

            – BeginnerDBA
            Jun 26 at 17:47












          • @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

            – Dan Guzman
            Jun 26 at 19:05











          • Very nice, thanks sir

            – BeginnerDBA
            Jun 27 at 13:55













          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "182"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f241302%2fway-to-find-when-system-health-file-is-rolling-over%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          6














          You can get all the system_health event files and their oldest event like this:



          DECLARE @file_name AS nvarchar(max);
          DECLARE @file_path AS nvarchar(max);

          SELECT
          @file_name =
          CAST(st.target_data AS xml).value(
          N'(EventFileTarget/File/@name)[1]', N'nvarchar(max)')
          FROM sys.dm_xe_sessions s
          INNER JOIN sys.dm_xe_session_targets st
          ON s.[address] = st.event_session_address
          WHERE
          st.target_name = 'event_file'
          AND s.[name] = 'system_health';


          SELECT @file_path = LEFT(
          @file_name,
          LEN(@file_name) - CHARINDEX('', REVERSE(@file_name)) + 1);

          SELECT
          files.[file_name],
          MIN(CAST(files.event_data AS XML).value(N'(event/@timestamp)[1]', N'datetime')) AS oldest_event
          FROM sys.fn_xe_file_target_read_file
          (
          @file_path + 'system_health*',
          null, null, null
          ) files
          GROUP BY files.[file_name]
          OPTION(NO_PERFORMANCE_SPOOL, QUERYTRACEON 8649);


          Screenshot of SSMS results



          Note: for versions of SQL Server that don't support the NO_PERFORMANCE_SPOOL query hint (prior to SQL Server 2016), you can replace that with with QUERYTRACEON 8690 (see Spool operator and trace flag 8690 for details).



          The code above



          • gets the filename for the currently-active event file,

          • then attempts to extract the path using this method,

          • then uses the sys.fn_xe_file_target_read_file dynamic management function to get oldest event from each file

          Hat tip to Erik Darling for suggesting the query hints, which sped things up significantly in my tests



          So one way to accomplish your goal would be to run that query as a scheduled agent job, and log the results to a table. Then you'd be able to see when the "oldest event" changes for each file (AKA when the file rolls over).



          Recall that files can roll over for a number of different reasons.



          If performance is an issue, and you are comfortable with PowerShell, you are likely much better off using the approach offered by Dan Guzman here.






          share|improve this answer

























          • I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

            – BeginnerDBA
            Jun 26 at 18:21











          • @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

            – Josh Darnell
            Jun 26 at 18:26











          • Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

            – BeginnerDBA
            9 hours ago











          • @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

            – Josh Darnell
            4 hours ago















          6














          You can get all the system_health event files and their oldest event like this:



          DECLARE @file_name AS nvarchar(max);
          DECLARE @file_path AS nvarchar(max);

          SELECT
          @file_name =
          CAST(st.target_data AS xml).value(
          N'(EventFileTarget/File/@name)[1]', N'nvarchar(max)')
          FROM sys.dm_xe_sessions s
          INNER JOIN sys.dm_xe_session_targets st
          ON s.[address] = st.event_session_address
          WHERE
          st.target_name = 'event_file'
          AND s.[name] = 'system_health';


          SELECT @file_path = LEFT(
          @file_name,
          LEN(@file_name) - CHARINDEX('', REVERSE(@file_name)) + 1);

          SELECT
          files.[file_name],
          MIN(CAST(files.event_data AS XML).value(N'(event/@timestamp)[1]', N'datetime')) AS oldest_event
          FROM sys.fn_xe_file_target_read_file
          (
          @file_path + 'system_health*',
          null, null, null
          ) files
          GROUP BY files.[file_name]
          OPTION(NO_PERFORMANCE_SPOOL, QUERYTRACEON 8649);


          Screenshot of SSMS results



          Note: for versions of SQL Server that don't support the NO_PERFORMANCE_SPOOL query hint (prior to SQL Server 2016), you can replace that with with QUERYTRACEON 8690 (see Spool operator and trace flag 8690 for details).



          The code above



          • gets the filename for the currently-active event file,

          • then attempts to extract the path using this method,

          • then uses the sys.fn_xe_file_target_read_file dynamic management function to get oldest event from each file

          Hat tip to Erik Darling for suggesting the query hints, which sped things up significantly in my tests



          So one way to accomplish your goal would be to run that query as a scheduled agent job, and log the results to a table. Then you'd be able to see when the "oldest event" changes for each file (AKA when the file rolls over).



          Recall that files can roll over for a number of different reasons.



          If performance is an issue, and you are comfortable with PowerShell, you are likely much better off using the approach offered by Dan Guzman here.






          share|improve this answer

























          • I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

            – BeginnerDBA
            Jun 26 at 18:21











          • @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

            – Josh Darnell
            Jun 26 at 18:26











          • Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

            – BeginnerDBA
            9 hours ago











          • @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

            – Josh Darnell
            4 hours ago













          6












          6








          6







          You can get all the system_health event files and their oldest event like this:



          DECLARE @file_name AS nvarchar(max);
          DECLARE @file_path AS nvarchar(max);

          SELECT
          @file_name =
          CAST(st.target_data AS xml).value(
          N'(EventFileTarget/File/@name)[1]', N'nvarchar(max)')
          FROM sys.dm_xe_sessions s
          INNER JOIN sys.dm_xe_session_targets st
          ON s.[address] = st.event_session_address
          WHERE
          st.target_name = 'event_file'
          AND s.[name] = 'system_health';


          SELECT @file_path = LEFT(
          @file_name,
          LEN(@file_name) - CHARINDEX('', REVERSE(@file_name)) + 1);

          SELECT
          files.[file_name],
          MIN(CAST(files.event_data AS XML).value(N'(event/@timestamp)[1]', N'datetime')) AS oldest_event
          FROM sys.fn_xe_file_target_read_file
          (
          @file_path + 'system_health*',
          null, null, null
          ) files
          GROUP BY files.[file_name]
          OPTION(NO_PERFORMANCE_SPOOL, QUERYTRACEON 8649);


          Screenshot of SSMS results



          Note: for versions of SQL Server that don't support the NO_PERFORMANCE_SPOOL query hint (prior to SQL Server 2016), you can replace that with with QUERYTRACEON 8690 (see Spool operator and trace flag 8690 for details).



          The code above



          • gets the filename for the currently-active event file,

          • then attempts to extract the path using this method,

          • then uses the sys.fn_xe_file_target_read_file dynamic management function to get oldest event from each file

          Hat tip to Erik Darling for suggesting the query hints, which sped things up significantly in my tests



          So one way to accomplish your goal would be to run that query as a scheduled agent job, and log the results to a table. Then you'd be able to see when the "oldest event" changes for each file (AKA when the file rolls over).



          Recall that files can roll over for a number of different reasons.



          If performance is an issue, and you are comfortable with PowerShell, you are likely much better off using the approach offered by Dan Guzman here.






          share|improve this answer















          You can get all the system_health event files and their oldest event like this:



          DECLARE @file_name AS nvarchar(max);
          DECLARE @file_path AS nvarchar(max);

          SELECT
          @file_name =
          CAST(st.target_data AS xml).value(
          N'(EventFileTarget/File/@name)[1]', N'nvarchar(max)')
          FROM sys.dm_xe_sessions s
          INNER JOIN sys.dm_xe_session_targets st
          ON s.[address] = st.event_session_address
          WHERE
          st.target_name = 'event_file'
          AND s.[name] = 'system_health';


          SELECT @file_path = LEFT(
          @file_name,
          LEN(@file_name) - CHARINDEX('', REVERSE(@file_name)) + 1);

          SELECT
          files.[file_name],
          MIN(CAST(files.event_data AS XML).value(N'(event/@timestamp)[1]', N'datetime')) AS oldest_event
          FROM sys.fn_xe_file_target_read_file
          (
          @file_path + 'system_health*',
          null, null, null
          ) files
          GROUP BY files.[file_name]
          OPTION(NO_PERFORMANCE_SPOOL, QUERYTRACEON 8649);


          Screenshot of SSMS results



          Note: for versions of SQL Server that don't support the NO_PERFORMANCE_SPOOL query hint (prior to SQL Server 2016), you can replace that with with QUERYTRACEON 8690 (see Spool operator and trace flag 8690 for details).



          The code above



          • gets the filename for the currently-active event file,

          • then attempts to extract the path using this method,

          • then uses the sys.fn_xe_file_target_read_file dynamic management function to get oldest event from each file

          Hat tip to Erik Darling for suggesting the query hints, which sped things up significantly in my tests



          So one way to accomplish your goal would be to run that query as a scheduled agent job, and log the results to a table. Then you'd be able to see when the "oldest event" changes for each file (AKA when the file rolls over).



          Recall that files can roll over for a number of different reasons.



          If performance is an issue, and you are comfortable with PowerShell, you are likely much better off using the approach offered by Dan Guzman here.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 26 at 18:17

























          answered Jun 24 at 19:57









          Josh DarnellJosh Darnell

          10.1k3 gold badges23 silver badges50 bronze badges




          10.1k3 gold badges23 silver badges50 bronze badges












          • I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

            – BeginnerDBA
            Jun 26 at 18:21











          • @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

            – Josh Darnell
            Jun 26 at 18:26











          • Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

            – BeginnerDBA
            9 hours ago











          • @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

            – Josh Darnell
            4 hours ago

















          • I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

            – BeginnerDBA
            Jun 26 at 18:21











          • @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

            – Josh Darnell
            Jun 26 at 18:26











          • Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

            – BeginnerDBA
            9 hours ago











          • @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

            – Josh Darnell
            4 hours ago
















          I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

          – BeginnerDBA
          Jun 26 at 18:21





          I did and works. On side note, is that use documented or supported. Just hoping running inside SQL agent should not run into issue.

          – BeginnerDBA
          Jun 26 at 18:21













          @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

          – Josh Darnell
          Jun 26 at 18:26





          @BeginnerDBA I think that since it was recommended by a support engineer in that blog post, that it is considered officially documented (and thus supported). I'm no expert though.

          – Josh Darnell
          Jun 26 at 18:26













          Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

          – BeginnerDBA
          9 hours ago





          Time returned is in UTC as i am checking which confuses sometime, is there a way you can update the answer to display that based on server settings for time zone?

          – BeginnerDBA
          9 hours ago













          @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

          – Josh Darnell
          4 hours ago





          @BeginnerDBA I haven't had a chance to check on this (busy day), but have you tried something like this? stackoverflow.com/questions/8038744/…

          – Josh Darnell
          4 hours ago













          6














          Below is a powershell example that summarizes events by name from the local system_health target files using the new Microsoft [SqlServer.XEvent PowerShell module][1]. I've found it's much faster to process high event volumes using .NET/PowerShell than parsing XML in T-SQL. You can schedule this as a SQL Agent job to identify what is driving the event activity and take corrective action if needed.



          # Install the SqlServer.XEvent module from an admin PowerShell session before running this script:
          # Install-Module -Name SqlServer.XEvent

          # get list of system_health trace files
          Function Get-XeFiles()
          $connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          try

          $xe_files = Get-XeFiles
          foreach($xe_file in $xe_files)
          try Group-Object -Property Name -NoElement
          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw





          catch
          throw



          Sample output:



          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057213063750000.xel

          Count Name
          ----- ----
          860 sp_server_diagnostics_component_result
          1072 scheduler_monitor_system_health_ring_buffer_recorded
          2 connectivity_ring_buffer_recorded
          1 security_error_ring_buffer_recorded

          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057856050380000.xel

          Count Name
          ----- ----
          1312 sp_server_diagnostics_component_result
          1644 scheduler_monitor_system_health_ring_buffer_recorded
          28 scheduler_monitor_non_yielding_ring_buffer_recorded
          4 connectivity_ring_buffer_recorded
          2 error_reported
          2 wait_info
          6 security_error_ring_buffer_recorded


          EDIT:



          This can also be done remotely and against multiple servers with a single script as long as the trace folder is available remotely via a share. The example below runs against each server in a list and uses a UNC path to access the trace files. Because this version uses the drive letter admin share, it must run under a Windows account that has Windows admin permissions on the remote box. A less privileged account can be used if you create a share on each server and use that share name instead.



          # get list of system_health trace files with admin share UNC path
          Function Get-XeFiles($serverName)
          $connectionString = "Data Source=$serverName;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          # change driver letter to admin share UNC path (e.g. "D:" to "\servernamed$")
          $traceFileDirectory = "\$serverName$($traceFileDirectory.Replace(":", "$"))"
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          # specify list of servers here
          $serverList = @(
          "YourServer1"
          ,"YourServer2"
          ,"YourServer3"
          )

          try
          foreach($server in $serverList)

          $xe_files = Get-XeFiles -serverName $server
          foreach($xe_file in $xe_files)
          try Format-Table -AutoSize

          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw






          catch
          throw






          share|improve this answer

























          • Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

            – BeginnerDBA
            Jun 26 at 17:47












          • @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

            – Dan Guzman
            Jun 26 at 19:05











          • Very nice, thanks sir

            – BeginnerDBA
            Jun 27 at 13:55















          6














          Below is a powershell example that summarizes events by name from the local system_health target files using the new Microsoft [SqlServer.XEvent PowerShell module][1]. I've found it's much faster to process high event volumes using .NET/PowerShell than parsing XML in T-SQL. You can schedule this as a SQL Agent job to identify what is driving the event activity and take corrective action if needed.



          # Install the SqlServer.XEvent module from an admin PowerShell session before running this script:
          # Install-Module -Name SqlServer.XEvent

          # get list of system_health trace files
          Function Get-XeFiles()
          $connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          try

          $xe_files = Get-XeFiles
          foreach($xe_file in $xe_files)
          try Group-Object -Property Name -NoElement
          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw





          catch
          throw



          Sample output:



          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057213063750000.xel

          Count Name
          ----- ----
          860 sp_server_diagnostics_component_result
          1072 scheduler_monitor_system_health_ring_buffer_recorded
          2 connectivity_ring_buffer_recorded
          1 security_error_ring_buffer_recorded

          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057856050380000.xel

          Count Name
          ----- ----
          1312 sp_server_diagnostics_component_result
          1644 scheduler_monitor_system_health_ring_buffer_recorded
          28 scheduler_monitor_non_yielding_ring_buffer_recorded
          4 connectivity_ring_buffer_recorded
          2 error_reported
          2 wait_info
          6 security_error_ring_buffer_recorded


          EDIT:



          This can also be done remotely and against multiple servers with a single script as long as the trace folder is available remotely via a share. The example below runs against each server in a list and uses a UNC path to access the trace files. Because this version uses the drive letter admin share, it must run under a Windows account that has Windows admin permissions on the remote box. A less privileged account can be used if you create a share on each server and use that share name instead.



          # get list of system_health trace files with admin share UNC path
          Function Get-XeFiles($serverName)
          $connectionString = "Data Source=$serverName;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          # change driver letter to admin share UNC path (e.g. "D:" to "\servernamed$")
          $traceFileDirectory = "\$serverName$($traceFileDirectory.Replace(":", "$"))"
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          # specify list of servers here
          $serverList = @(
          "YourServer1"
          ,"YourServer2"
          ,"YourServer3"
          )

          try
          foreach($server in $serverList)

          $xe_files = Get-XeFiles -serverName $server
          foreach($xe_file in $xe_files)
          try Format-Table -AutoSize

          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw






          catch
          throw






          share|improve this answer

























          • Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

            – BeginnerDBA
            Jun 26 at 17:47












          • @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

            – Dan Guzman
            Jun 26 at 19:05











          • Very nice, thanks sir

            – BeginnerDBA
            Jun 27 at 13:55













          6












          6








          6







          Below is a powershell example that summarizes events by name from the local system_health target files using the new Microsoft [SqlServer.XEvent PowerShell module][1]. I've found it's much faster to process high event volumes using .NET/PowerShell than parsing XML in T-SQL. You can schedule this as a SQL Agent job to identify what is driving the event activity and take corrective action if needed.



          # Install the SqlServer.XEvent module from an admin PowerShell session before running this script:
          # Install-Module -Name SqlServer.XEvent

          # get list of system_health trace files
          Function Get-XeFiles()
          $connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          try

          $xe_files = Get-XeFiles
          foreach($xe_file in $xe_files)
          try Group-Object -Property Name -NoElement
          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw





          catch
          throw



          Sample output:



          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057213063750000.xel

          Count Name
          ----- ----
          860 sp_server_diagnostics_component_result
          1072 scheduler_monitor_system_health_ring_buffer_recorded
          2 connectivity_ring_buffer_recorded
          1 security_error_ring_buffer_recorded

          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057856050380000.xel

          Count Name
          ----- ----
          1312 sp_server_diagnostics_component_result
          1644 scheduler_monitor_system_health_ring_buffer_recorded
          28 scheduler_monitor_non_yielding_ring_buffer_recorded
          4 connectivity_ring_buffer_recorded
          2 error_reported
          2 wait_info
          6 security_error_ring_buffer_recorded


          EDIT:



          This can also be done remotely and against multiple servers with a single script as long as the trace folder is available remotely via a share. The example below runs against each server in a list and uses a UNC path to access the trace files. Because this version uses the drive letter admin share, it must run under a Windows account that has Windows admin permissions on the remote box. A less privileged account can be used if you create a share on each server and use that share name instead.



          # get list of system_health trace files with admin share UNC path
          Function Get-XeFiles($serverName)
          $connectionString = "Data Source=$serverName;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          # change driver letter to admin share UNC path (e.g. "D:" to "\servernamed$")
          $traceFileDirectory = "\$serverName$($traceFileDirectory.Replace(":", "$"))"
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          # specify list of servers here
          $serverList = @(
          "YourServer1"
          ,"YourServer2"
          ,"YourServer3"
          )

          try
          foreach($server in $serverList)

          $xe_files = Get-XeFiles -serverName $server
          foreach($xe_file in $xe_files)
          try Format-Table -AutoSize

          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw






          catch
          throw






          share|improve this answer















          Below is a powershell example that summarizes events by name from the local system_health target files using the new Microsoft [SqlServer.XEvent PowerShell module][1]. I've found it's much faster to process high event volumes using .NET/PowerShell than parsing XML in T-SQL. You can schedule this as a SQL Agent job to identify what is driving the event activity and take corrective action if needed.



          # Install the SqlServer.XEvent module from an admin PowerShell session before running this script:
          # Install-Module -Name SqlServer.XEvent

          # get list of system_health trace files
          Function Get-XeFiles()
          $connectionString = "Data Source=.;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          try

          $xe_files = Get-XeFiles
          foreach($xe_file in $xe_files)
          try Group-Object -Property Name -NoElement
          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw





          catch
          throw



          Sample output:



          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057213063750000.xel

          Count Name
          ----- ----
          860 sp_server_diagnostics_component_result
          1072 scheduler_monitor_system_health_ring_buffer_recorded
          2 connectivity_ring_buffer_recorded
          1 security_error_ring_buffer_recorded

          Summary for file D:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogsystem_health_0_132057856050380000.xel

          Count Name
          ----- ----
          1312 sp_server_diagnostics_component_result
          1644 scheduler_monitor_system_health_ring_buffer_recorded
          28 scheduler_monitor_non_yielding_ring_buffer_recorded
          4 connectivity_ring_buffer_recorded
          2 error_reported
          2 wait_info
          6 security_error_ring_buffer_recorded


          EDIT:



          This can also be done remotely and against multiple servers with a single script as long as the trace folder is available remotely via a share. The example below runs against each server in a list and uses a UNC path to access the trace files. Because this version uses the drive letter admin share, it must run under a Windows account that has Windows admin permissions on the remote box. A less privileged account can be used if you create a share on each server and use that share name instead.



          # get list of system_health trace files with admin share UNC path
          Function Get-XeFiles($serverName)
          $connectionString = "Data Source=$serverName;Initial Catalog=tempdb;Integrated Security=SSPI";
          $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString);
          $connection.Open();
          $query = @"
          WITH
          --get full path to current system_health trace file
          CurrentSystemHealthTraceFile AS (
          SELECT CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') AS FileName
          FROM sys.dm_xe_session_targets
          WHERE
          target_name = 'event_file'
          AND CAST(target_data AS xml).value('(/EventFileTarget/File/@name)[1]', 'varchar(255)') LIKE '%system[_]health%'
          )
          --get system_health trace folder
          , TraceDirectory AS (
          SELECT
          REVERSE(SUBSTRING(REVERSE(FileName), CHARINDEX(N'', REVERSE(FileName)), 255)) AS TraceDirectoryPath
          FROM CurrentSystemHealthTraceFile
          )
          SELECT TraceDirectoryPath
          FROM TraceDirectory;
          "@

          $command = New-Object System.Data.SqlClient.SqlCommand($query, $connection)
          $traceFileDirectory = $command.ExecuteScalar()
          # change driver letter to admin share UNC path (e.g. "D:" to "\servernamed$")
          $traceFileDirectory = "\$serverName$($traceFileDirectory.Replace(":", "$"))"
          $connection.Close()

          $xe_files = Get-Item "$($traceFileDirectory)system_health_*.xel"
          return $xe_files



          # specify list of servers here
          $serverList = @(
          "YourServer1"
          ,"YourServer2"
          ,"YourServer3"
          )

          try
          foreach($server in $serverList)

          $xe_files = Get-XeFiles -serverName $server
          foreach($xe_file in $xe_files)
          try Format-Table -AutoSize

          catch
          if(($_.Exception.GetType().Name -eq "AggregateException") -and ($_.Exception.InnerException -ne $null) -and ($_.Exception.InnerException.GetType().Name -eq "IOException"))
          # ignore error due to active trace file
          Write-Host "$($_.Exception.InnerException.Message)"

          else
          # rethrow other errors
          throw






          catch
          throw







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jun 26 at 19:04

























          answered Jun 24 at 22:49









          Dan GuzmanDan Guzman

          15k2 gold badges18 silver badges39 bronze badges




          15k2 gold badges18 silver badges39 bronze badges












          • Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

            – BeginnerDBA
            Jun 26 at 17:47












          • @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

            – Dan Guzman
            Jun 26 at 19:05











          • Very nice, thanks sir

            – BeginnerDBA
            Jun 27 at 13:55

















          • Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

            – BeginnerDBA
            Jun 26 at 17:47












          • @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

            – Dan Guzman
            Jun 26 at 19:05











          • Very nice, thanks sir

            – BeginnerDBA
            Jun 27 at 13:55
















          Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

          – BeginnerDBA
          Jun 26 at 17:47






          Thanks, i will check this out. However iam wondering if i have 100+ servers to check do i have to install the module in each . Excuse me for my lack of my knw in PS

          – BeginnerDBA
          Jun 26 at 17:47














          @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

          – Dan Guzman
          Jun 26 at 19:05





          @BeginnerDBA, you can run the script from a single server. See the edit in my answer.

          – Dan Guzman
          Jun 26 at 19:05













          Very nice, thanks sir

          – BeginnerDBA
          Jun 27 at 13:55





          Very nice, thanks sir

          – BeginnerDBA
          Jun 27 at 13:55

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Database Administrators Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f241302%2fway-to-find-when-system-health-file-is-rolling-over%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?