functions/Watch-DbaXESession.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
function Watch-DbaXESession {
    <#
    .SYNOPSIS
    Watch live XEvent Data as it happens
 
    .DESCRIPTION
    Watch live XEvent Data as it happens - this command runs until you stop the session, kill the PowerShell session, or Ctrl-C a few hundred times ;).
 
    Thanks to Dave Mason (@BeginTry) for some straightforward code samples https://itsalljustelectrons.blogspot.be/2017/01/SQL-Server-Extended-Event-Handling-Via-Powershell.html
 
    .PARAMETER SqlInstance
    The SQL Instance that you're connecting to.
 
    .PARAMETER SqlCredential
    Credential object used to connect to the SQL Server as a different user
 
    .PARAMETER Session
    Only return a specific session. This parameter is auto-populated.
 
    .PARAMETER Raw
    Returns the Microsoft.SqlServer.XEvent.Linq.QueryableXEventData enumeration object
 
    .PARAMETER InputObject
    Internal parameter
 
    .PARAMETER EnableException
    By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
    This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
    Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
    .NOTES
    Tags: Xevent
    Website: https://dbatools.io
    Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
    License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
    .LINK
    https://dbatools.io/Watch-DbaXESession
 
    .EXAMPLE
    Watch-DbaXESession -SqlInstance sql2017 -Session system_health
 
    Shows events for the system_health session as it happens
 
    .EXAMPLE
    Watch-DbaXESession -SqlInstance sql2017 -Session system_health | Export-Csv -NoTypeInformation -Path C:\temp\system_health.csv
 
    Exports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session.
     
    .EXAMPLE
    Get-DbaXESession -SqlInstance sql2017 -Session system_health | Start-DbaXESession | Watch-DbaXESession | Export-Csv -NoTypeInformation -Path C:\temp\system_health.csv
 
    Exports live events to CSV. Ctrl-C may not not cancel out of it - fastest way is to stop the session.
#>

    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [parameter(ValueFromPipeline, ParameterSetName = "instance", Mandatory)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Session,
        [parameter(ValueFromPipeline, ParameterSetName = "piped", Mandatory)]
        [Microsoft.SqlServer.Management.XEvent.Session]$InputObject,
        [switch]$Raw,
        [switch][Alias('Silent')]
        $EnableException
    )
    process {
        if (-not $SqlInstance) {
            $server = $InputObject.Parent
        }
        else {
            try {
                Write-Message -Level Verbose -Message "Connecting to $SqlInstance"
                $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential -MinimumVersion 11
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $SqlInstance -Continue
            }
            $SqlConn = $server.ConnectionContext.SqlConnectionObject
            $SqlStoreConnection = New-Object Microsoft.SqlServer.Management.Sdk.Sfc.SqlStoreConnection $SqlConn
            $XEStore = New-Object  Microsoft.SqlServer.Management.XEvent.XEStore $SqlStoreConnection
            Write-Message -Level Verbose -Message "Getting XEvents Sessions on $SqlInstance."
            $InputObject = $XEStore.sessions | Where-Object Name -eq $Session | Select-Object -First 1
        }
        
        if ($InputObject) {
            $status = $InputObject.Status
            if ($status -ne "Running") {
                Stop-Function -Message "$($InputObject.Name) is in a $status state"
                return
            }
            
            # Setup all columns for csv but do it in an order
            $columns = @("name", "timestamp")
            $newcolumns = @()
            
            $fields = ($InputObject.Events.EventFields.Name | Select-Object -Unique)
            foreach ($column in $fields) {
                $newcolumns += $column.TrimStart("collect_")
            }
            
            $actions = ($InputObject.Events.Actions.Name | Select-Object -Unique)
            foreach ($action in $actions) {
                $newcolumns += ($action -Split '\.')[-1]
            }
            
            $newcolumns = $newcolumns | Sort-Object
            $columns = ($columns += $newcolumns) | Select-Object -Unique
            
            try {
                $xevent = New-Object -TypeName Microsoft.SqlServer.XEvent.Linq.QueryableXEventData(
                    ($server.ConnectionContext.ConnectionString),
                    ($InputObject.Name),
                    [Microsoft.SqlServer.XEvent.Linq.EventStreamSourceOptions]::EventStream,
                    [Microsoft.SqlServer.XEvent.Linq.EventStreamCacheOptions]::DoNotCache
                )
                
                if ($raw) {
                    return $xevent
                }
                
                # make it pretty
                foreach ($event in $xevent) {
                    $hash = [ordered]@{}
                    
                    foreach ($column in $columns) {
                            $null = $hash.Add($column, $event.$column) # this basically adds name and timestamp then nulls
                    }
                    
                    foreach ($action in $event.Actions) {
                        $hash[$action.Name] = $action.Value
                    }
                    
                    foreach ($field in $event.Fields) {
                        $hash[$field.Name] = $field.Value
                    }
                    
                    [pscustomobject]($hash)
                }
            }
            catch {
                Start-Sleep 1
                $status = Get-DbaXESession -SqlInstance $server -Session $Session
                if ($status.Status -ne "Running") {
                    Stop-Function -Message "$($InputObject.Name) was stopped"
                }
                else {
                    Stop-Function -Message "Failure" -ErrorRecord $_ -Target $session
                }
            }
            finally {
                if ($xevent -is [IDisposable]) {
                    $xevent.Dispose()
                }
            }
        }
        else {
            Stop-Function -Message "Session not found" -Target $session
        }
    }
}