functions/Get-DbaSchemaChangeHistory.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
function Get-DbaSchemaChangeHistory {
    <#
 .SYNOPSIS
 Gets DDL changes logged in the system trace.
 
 .DESCRIPTION
 Queries the default system trace for any DDL changes in the specified timeframe
 Only works with SQL 2005 and later, as the system trace didn't exist before then
 
 .PARAMETER SqlInstance
 SQL Server name or SMO object representing the SQL Server to connect to. This can be a collection and receive pipeline input to allow the function
 to be executed against multiple SQL Server instances.
 
 .PARAMETER SqlCredential
 SqlCredential object to connect as. If not specified, current Windows login will be used.
 
 .PARAMETER Database
 The database(s) to process - this list is auto-populated from the server. If unspecified, all databases will be processed.
 
 .PARAMETER ExcludeDatabase
 The database(s) to exclude - this list is auto-populated from the server
   
 .PARAMETER Since
 A date from which DDL changes should be returned. Default is to start at the beggining of the current trace file
 
 .PARAMETER Object
 The name of a SQL Server object you want to look for changes on
 
 .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: Migration, Backup, Databases
 Author: Stuart Moore (@napalmgram - http://stuart-moore.com)
  
 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/Get-DbaSchemaChangeHistory
 
 .EXAMPLE
 Get-DbaSchemaChangeHistory -SqlInstance localhost
  
 Returns all DDL changes made in all databases on the SQL Server instance localhost since the system trace began
 
 .EXAMPLE
 Get-DbaSchemaChangeHistory -SqlInstance localhost -Since (Get-Date).AddDays(-7)
 
 Returns all DDL changes made in all databases on the SQL Server instance localhost in the last 7 days
 
 .EXAMPLE
 Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance, Prod -Since (Get-Date).AddDays(-7)
 
 Returns all DDL changes made in the Prod and Finance databases on the SQL Server instance localhost in the last 7 days
  
 .EXAMPLE
 Get-DbaSchemaChangeHistory -SqlInstance localhost -Database Finance -Object AccountsTable -Since (Get-Date).AddDays(-7)
 
 Returns all DDL changes made to the AccountsTable object in the Finance database on the SQL Server instance localhost in the last 7 days
 
 #>

    
    [CmdletBinding()]
    param (
        [parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $True)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [Alias("Credential")]
        [PSCredential]
        $SqlCredential,
        [Alias("Databases")]
        [object[]]$Database,
        [object[]]$ExcludeDatabase,
        [DbaDateTime]$Since,
        [string[]]$Object,
        [switch][Alias('Silent')]$EnableException
    )
    
    process {
        foreach ($instance in $SqlInstance) {
            Write-Message -Level Verbose -Message "Attempting to connect to $instance"
            
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if ($Server.Version.Major -le 8) {
                Stop-Function -Message "This command doesn't support SQL Server 2000, sorry about that" 
                return
            }
            $TraceFileQuery = "select path from sys.traces where is_default = 1"
            
            $TraceFile = $server.Query($TraceFileQuery) | Select-Object Path
            
            $Databases = $server.Databases
            
            if ($Database) { $Databases = $Databases | Where-Object Name -in $database }
            
            if ($ExcludeDatabase) { $Databases = $Databases | Where-Object Name -notin $ExcludeDatabase }
            
            foreach ($db in $Databases) {
                if ($db.IsAccessible -eq $false) {
                    Stop-Function -Message "$db on $server is inaccessible" -Continue
                }
                
                $sql = "select SERVERPROPERTY('MachineName') AS ComputerName,
      ISNULL(SERVERPROPERTY('InstanceName'), 'MSSQLSERVER') AS InstanceName,
      SERVERPROPERTY('ServerName') AS SqlInstance,
      tt.databasename as 'DatabaseName',
      starttime as 'DateModified',
      Sessionloginname as 'LoginName',
      NTusername as 'UserName',
      applicationname as 'ApplicationName',
      case eventclass
       When '46' Then 'Create'
       when '47' Then 'Drop'
       when '164' then 'Alter'
      end as 'DDLOperation',
      s.name+'.'+o.name as 'Object',
      o.type_desc as 'ObjectType'
      from
      sys.objects o inner join
      sys.schemas s on s.schema_id=o.schema_id
      cross apply (select * from ::fn_trace_gettable('$($TraceFile.path)',default) where ObjectID=o.object_id ) tt
      where tt.objecttype not in (21587)
      and tt.DatabaseID=db_id()
      and tt.EventSubClass=0"

                
                if ($null -ne $since) {
                    $sql =  $sql +" and tt.StartTime>'$Since' "
                }
                if ($null -ne $object) {
                    $sql =  $sql + " and o.name in ('$($object -join ''',''')') "
                }
                
                $sql =  $sql + " order by tt.StartTime asc"
                Write-Message -Level Verbose -Message "Querying Database $db on $instance"
                Write-Message -Level Debug -Message "SQL: $sql"
                
                $db.Query($sql)  | Select-DefaultView -Property ComputerName, InstanceName, SqlInstance, DatabaseName, DateModified, LoginName, UserName, ApplicationName, DDLOperation, Object, ObjectType
            }    
        }
    }
}