SQLExtensions.psm1

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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
function Invoke-SQLQuery
{
    [CmdletBinding()]
    [OutputType([System.Data.DataTable])]
    param 
    (
        #SqlConnection
        [Parameter(Mandatory=$true)]
        [System.Data.SqlClient.SqlConnection]$SqlConnection,    

        #Query
        [Parameter(Mandatory=$true)]
        [string]$Query,

        #TimeoutInSeconds
        [Parameter(Mandatory=$false)]
        [int]$TimeoutInSeconds = 60
    )
    
    Process
    {
        #Execute Query
        try
        {
            Write-Verbose "Execute Query started"

                $Command = $SqlConnection.CreateCommand()
                $Command.CommandText = $Query
                $Command.CommandTimeout = $TimeoutInSeconds
                $SqlResult = $Command.ExecuteReader()
                if ($SqlResult) {
                    $result = New-Object -TypeName System.Data.DataTable
                    $result.Load($SqlResult)
                    if ($result)
                    {
                        $result
                    }
                }
      
            Write-Verbose "Execute Query completed"
        }
        catch
        {
            Write-Error "Execute Query failed. Details: $_" -ErrorAction 'Stop'
        }
    }
}

function Get-SqlInstalledComponents
{
    [CmdletBinding()]
    [OutputType([object])]
    param
    (
        #VersionNumber
        [Parameter(Mandatory=$true,ParameterSetName='NoRemoting_Default')]
        [ValidateSet('100','110','120','130')]
        [string]$VersionNumber,

        [Parameter(Mandatory=$false,ParameterSetName='NoRemoting_Default')]
        [string]$InstanceName
    )
    
    Begin
    {
        $RegPropsToExclude = 'PSPath','PSParentPath','PSChildName','PSDrive','PSProvider'

        $SqlRegLocation = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server'
        $SqlSharedComponentsRegLocation = "$SqlRegLocation\$VersionNumber\ConfigurationState"
        $SqlInstanceComponentsRegLocation = "$SqlRegLocation\Instance Names"
    }

    Process
    {
        $Result = @{
            SqlDetected=$false
            Shared=@()
            Instances=@{
                RS=@()
                SQL=@()
            }
        }

        $SqlInstalled = Test-Path -Path $SqlRegLocation
        if ($SqlInstalled)
        {
            $Result['SqlDetected'] = $true

            #Get Shared Components
            try
            {
                $SqlSharedComponentsTemp = Get-ItemProperty -Path $SqlSharedComponentsRegLocation -Name 'SQL_*' -ErrorAction Stop
                $SqlSharedComponentsTemp = $SqlSharedComponentsTemp.psobject.Properties | Where-Object {($RegPropsToExclude -notcontains $_.Name) -and ($_.Value -eq 1)} | select -ExpandProperty Name
                $Result['Shared'] += $SqlSharedComponentsTemp

                if(([int]$VersionNumber) -eq 130)
                {
                    if((Test-Path -Path "$SqlRegLocation\$VersionNumber\Tools\Setup\SQL_SSMS_Adv") -and 
                        ((Get-ItemProperty -Path "$SqlRegLocation\$VersionNumber\Tools\Setup\SQL_SSMS_Adv").FeatureList -like "*SQL_SSMS_Adv=3*"))
                    {
                        $Result['Shared'] += 'SQL_SSMS_Adv'
                        $Result['Shared'] += 'SQL_SSMS_Full'
                    }
                }

                if(([int]$VersionNumber) -gt 130)
                {
                    throw "SSMS check is not implemented yet for versions above 130"
                }
            }
            catch
            {

            }

            #Get RS Instance Components
            try
            {
                $SqlRsInstanceComponentsTemp = Get-ItemProperty -Path "$SqlInstanceComponentsRegLocation\RS" -ErrorAction Stop
                $SqlRsInstanceComponentsTemp = $SqlRsInstanceComponentsTemp.psobject.Properties | Where-Object {($RegPropsToExclude -notcontains $_.Name)} | foreach {
                    [pscustomobject]@{
                        Name=$_.Value
                        InstanceName=$_.Name
                    }
                }

                if ($PSBoundParameters.ContainsKey('InstanceName'))
                {
                    $SqlRsInstanceComponentsTemp = $SqlRsInstanceComponentsTemp | Where-Object {$_.InstanceName -eq $InstanceName}
                }

                $Result['Instances']['RS'] += $SqlRsInstanceComponentsTemp
            }
            catch
            {

            }

            #Get Sql Instance Components
            try
            {
                $SqlSqlInstanceComponentsTemp = Get-ItemProperty -Path "$SqlInstanceComponentsRegLocation\Sql" -ErrorAction Stop
                $SqlSqlInstanceComponentsTemp = $SqlSqlInstanceComponentsTemp.psobject.Properties | Where-Object {($RegPropsToExclude -notcontains $_.Name)} | foreach {
                    [pscustomobject]@{
                        Name=$_.Value
                        InstanceName=$_.Name
                    }
                }

                if ($PSBoundParameters.ContainsKey('InstanceName'))
                {
                    $SqlSqlInstanceComponentsTemp = $SqlSqlInstanceComponentsTemp | Where-Object {$_.InstanceName -eq $InstanceName}
                }

                $Result['Instances']['Sql'] += $SqlSqlInstanceComponentsTemp
            }
            catch
            {

            }

        }

        #Return Result
        [pscustomobject]$Result
    }

    End
    {

    }
}

function New-SqlConnection
{
    [CmdletBinding()]
    [OutputType([System.Data.SqlClient.SqlConnection])]
    param
    (
        #ConnectionString
        [Parameter(Mandatory=$true)]
        [string]$ConnectionString,

        #AccessToken
        [Parameter(Mandatory=$false)]
        [string]$AccessToken
    )

    Process
    {
        #Create New SqlConnection
        try
        {
            Write-Verbose "Create New SqlConnection started"

            $connection = New-Object -TypeName System.Data.SqlClient.SqlConnection
            
            $connection.ConnectionString = $connectionString
            if ($PSBoundParameters.ContainsKey('AccessToken'))
            {
                $connection.AccessToken = $AccessToken
            }
            $connection.Open()
            $connection
            Write-Verbose "Create New SqlConnection completed"
        }
        catch
        {
            Write-Error "Create New SqlConnection failed. Details: $_" -ErrorAction 'Stop'
        }
    }
}

function Test-SqlInstanceNameFormat
{
    [CmdletBinding()]
    param
    (
        [Parameter(Position=0, Mandatory=$true)]
        [AllowNull()]
        [AllowEmptyString()]
        [string]$SqlInstanceName
    )

    Begin 
    {
        $SqlReservedKeywords = @('MSSQLServer', 'ADD', 'ALL', 'ALTER', 'AND', 'ANY', 'AS', 'ASC', 'AUTHORIZATION', 'BACKUP', 'BEGIN', 'BETWEEN', 'BREAK', 'BROWSE', 'BULK', 'BY', 'CASCADE', 'CASE', 'CHECK', 'CHECKPOINT', 'CLOSE', 'CLUSTERED', 'COALESCE', 'COLLATE', 'COLUMN', 'COMMIT', 'COMPUTE', 'CONSTRAINT', 'CONTAINS', 'CONTAINSTABLE', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT', 'CURRENT_DATE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DBCC', 'DEALLOCATE', 'DECLARE', 'DEFAULT', 'DELETE', 'DENY', 'DESC', 'DISK', 'DISTINCT', 'DISTRIBUTED', 'DOUBLE', 'DROP', 'DUMP', 'ELSE', 'END', 'ERRLVL', 'ESCAPE', 'EXCEPT', 'EXEC', 'EXECUTE', 'EXISTS', 'EXIT', 'EXTERNAL', 'FETCH', 'FILE', 'FILLFACTOR', 'FOR', 'FOREIGN', 'FREETEXT', 'FREETEXTTABLE', 'FROM', 'FULL', 'FUNCTION', 'GOTO', 'GRANT', 'GROUP', 'HAVING', 'HOLDLOCK', 'IDENTITY', 'IDENTITY_INSERT', 'IDENTITYCOL', 'IF', 'IN', 'INDEX', 'INNER', 'INSERT', 'INTERSECT', 'INTO', 'IS', 'JOIN', 'KEY', 'KILL', 'LEFT', 'LIKE', 'LINENO', 'LOAD', 'MERGE', 'NATIONAL', 'NOCHECK', 'NONCLUSTERED', 'NOT', 'NULL', 'NULLIF', 'OF', 'OFF', 'OFFSETS', 'ON', 'OPEN', 'OPENDATASOURCE', 'OPENQUERY', 'OPENROWSET', 'OPENXML', 'OPTION', 'OR', 'ORDER', 'OUTER', 'OVER', 'PERCENT', 'PIVOT', 'PLAN', 'PRECISION', 'PRIMARY', 'PRINT', 'PROC', 'PROCEDURE', 'PUBLIC', 'RAISERROR', 'READ', 'READTEXT', 'RECONFIGURE', 'REFERENCES', 'REPLICATION', 'RESTORE', 'RESTRICT', 'RETURN', 'REVERT', 'REVOKE', 'RIGHT', 'ROLLBACK', 'ROWCOUNT', 'ROWGUIDCOL', 'RULE', 'SAVE', 'SCHEMA', 'SECURITYAUDIT', 'SELECT', 'SEMANTICKEYPHRASETABLE', 'SEMANTICSIMILARITYDETAILSTABLE', 'SEMANTICSIMILARITYTABLE', 'SESSION_USER', 'SET', 'SETUSER', 'SHUTDOWN', 'SOME', 'STATISTICS', 'SYSTEM_USER', 'TABLE', 'TABLESAMPLE', 'TEXTSIZE', 'THEN', 'TO', 'TOP', 'TRAN', 'TRANSACTION', 'TRIGGER', 'TRUNCATE', 'TRY_CONVERT', 'TSEQUAL', 'UNION', 'UNIQUE', 'UNPIVOT', 'UPDATE', 'UPDATETEXT', 'USE', 'USER', 'VALUES', 'VARYING', 'VIEW', 'WAITFOR', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WITHIN GROUP', 'WRITETEXT')
        $ForbiddenChars = @(' ','\',',',':',';',"'",'&','@','`')
    }

    Process
    {
        if([string]::IsNullOrWhiteSpace($SqlInstanceName)) { throw "The SQL Instance Name cannot be blank" }
        if("$SqlInstanceName".Length -gt 16) { throw "The SQL Instance Name must contain 16 characters or less" }
        if( -not [char]::IsLetter($SqlInstanceName, 0)) { throw "The SQL Instance Name must start with a letter" }
        if("$SqlInstanceName".Substring("$SqlInstanceName".Length - 1) -eq '_') { throw "The SQL Instance Name cannot end with an underscore" }
        $SqlReservedKeywords | foreach { if("$SqlInstanceName" -ilike $_) { throw "The SQL Instance Name cannot contain reserved keywords like $_" } }
        $ForbiddenChars | foreach { if("$SqlInstanceName" -ilike "*$_*") { throw "The SQL Instance Name contains invalid characters ($_)" } }
    }

    End
    {

    }
}