functions/Get-DbaProductKey.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
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
function Get-DbaProductKey {
<#
    .SYNOPSIS
        Gets SQL Server Product Keys from local or destination SQL Servers. Works with SQL Server 2005-2016
 
    .DESCRIPTION
        Using a string of servers, a text file, or Central Management Server to provide a list of servers, this script will go to each server and get the product key for all installed instances. Clustered instances are supported as well. Requires regular user access to the SQL instances, SMO installed locally, Remote Registry enabled and accessible by the account running the script.
 
        Uses key decoder by Jakob Bindslet (http://goo.gl/1jiwcB)
 
    .PARAMETER SqlInstance
        Allows you to specify a comma separated list of servers to query.
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER SqlCms
        Deprecated, pipe in from Get-DbaCmsRegServer
 
    .PARAMETER ServersFromFile
        Deprecated, pipe in from Get-Content
 
    .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: ProductKey
        Author: Chrissy LeMaire (@cl), netnerds.net
 
        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT
 
    .LINK
        https://dbatools.io/Get-DbaProductKey
 
    .EXAMPLE
        PS C:\> Get-DbaProductKey -SqlInstance winxp, sqlservera, sqlserver2014a, win2k8
 
        Gets SQL Server versions, editions and product keys for all instances within each server or workstation.
 
#>

    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline, Mandatory)]
        [Alias("ServerInstance", "SqlServer", "SqlInstances")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$SqlCms,
        [string]$ServersFromFile,
        [switch]$EnableException
    )

    begin {
        Function Unlock-SqlInstanceKey {
            [CmdletBinding()]
            param (
                [Parameter(Mandatory)]
                [byte[]]$data,
                [int]$version
            )
            try {
                if ($version -ge 11) { $binArray = ($data)[0 .. 66] }
                else { $binArray = ($data)[52 .. 66] }
                $charsArray = "B", "C", "D", "F", "G", "H", "J", "K", "M", "P", "Q", "R", "T", "V", "W", "X", "Y", "2", "3", "4", "6", "7", "8", "9"
                for ($i = 24; $i -ge 0; $i--) {
                    $k = 0
                    for ($j = 14; $j -ge 0; $j--) {
                        $k = $k * 256 -bxor $binArray[$j]
                        $binArray[$j] = [math]::truncate($k / 24)
                        $k = $k % 24
                    }
                    $productKey = $charsArray[$k] + $productKey
                    if (($i % 5 -eq 0) -and ($i -ne 0)) {
                        $productKey = "-" + $productKey
                    }
                }
            }
            catch {
                $productkey = "Cannot decode product key."
            }
            return $productKey
        }
    }

    process {
        if ($SqlCms) {
            Stop-Function -Message "Please pipe in servers using Get-DbaCmsRegServer instead"
            return
        }

        If ($ServersFromFile) {
            Stop-Function -Message "Please pipe in servers using Get-Content instead"
            return
        }

        foreach ($instance in $SqlInstance) {
            $computerName = $instance.ComputerName
            try {
                $regRoots = Get-DbaRegistryRoot -ComputerName $computerName -EnableException
            }
            catch {
                Stop-Function -Message "Can't access registry for $computerName. Is the Remote Registry service started?" -Continue
            }
            if ($instance.IsLocalhost) {
                $localmachine = [Microsoft.Win32.RegistryHive]::LocalMachine
                $defaultview = [Microsoft.Win32.RegistryView]::Default
                $reg = [Microsoft.Win32.RegistryKey]::OpenBaseKey($localmachine, $defaultview)
            }
            else {
                # Get IP for remote registry access. It's the most reliable.
                try { $ipaddr = ([System.Net.Dns]::GetHostAddresses($computerName)).IPAddressToString }
                catch {
                    Stop-Function -Message "Can't resolve $computerName. Skipping." -Continue
                }

                try {
                    $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $ipaddr)
                }
                catch {
                    Stop-Function -Message "Can't access registry for $computerName. Is the Remote Registry service started?" -Continue
                }
            }

            if (-not($regRoots)) {
                Stop-Function -Message "No instances found on $computerName. Skipping." -Continue
            }

            # Get Product Keys for all instances on the server.
            foreach ($instanceReg in $regRoots) {

                Write-Message -Level Verbose -Message "Connecting to $($instanceReg.SqlInstance)"
                try {
                    Write-Message -Level Verbose -Message "Connecting to $instance"
                    $server = Connect-SqlInstance -SqlInstance $instanceReg.SqlInstance -SqlCredential $SqlCredential -MinimumVersion 10
                }
                catch {
                    Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instanceReg.SqlInstance -Continue
                }

                $servicePack = $server.ProductLevel
                Write-Message -Level Debug -Message "$instance $instanceName version is $($server.VersionMajor)"

                switch ($server.VersionMajor) {
                    9 {
                        $sqlversion = "SQL Server 2005 $servicePack"
                        $findkeys = $reg.OpenSubKey("$($instanceReg.Path)\ProductID", $false)
                        foreach ($findkey in $findkeys.GetValueNames()) {
                            if ($findkey -like "DigitalProductID*") {
                                $key = @("$($instanceReg.Path)\ProductID\$findkey")
                            }
                        }
                    }
                    10 {
                        $sqlversion = "SQL Server 2008 $servicePack"
                        if ($server.VersionMinor -eq 50) {
                            $sqlversion = "SQL Server 2008 R2 $servicePack"
                        }
                        $key = @("$($instanceReg.Path)\Setup\DigitalProductID")
                    }
                    11 {
                        $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                        $sqlversion = "SQL Server 2012 $servicePack"
                    }
                    12 {
                        $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                        $sqlversion = "SQL Server 2014 $servicePack"
                    }
                    13 {
                        $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                        $sqlversion = "SQL Server 2016 $servicePack"
                    }
                    14 {
                        $key = @("$($instanceReg.Path)\Setup\DigitalProductID", "$($instanceReg.Path)\ClientSetup\DigitalProductID")
                        $sqlversion = "SQL Server 2017 $servicePack"
                    }
                    default {
                        Stop-Function -Message "SQL version not currently supported." -Continue
                    }
                }
                if ($server.Edition -notlike "*Express*") {
                    $sqlkey = ''
                    foreach ($k in $key) {
                        $subkey = Split-Path $k
                        $binaryvalue = Split-Path $k -Leaf
                        try {
                            $binarykey = $($reg.OpenSubKey($subkey)).GetValue($binaryvalue)
                            break
                        }
                        catch {
                            $binarykey = $null
                        }
                    }

                    if ($null -eq $binarykey) {
                        $sqlkey = "Could not read Product Key from registry on $computername"
                    }
                    else {
                        try {
                            $sqlkey = Unlock-SqlInstanceKey $binarykey $server.VersionMajor
                        }
                        catch {
                            $sqlkey = "Unable to unlock key"
                        }
                    }
                }
                else {
                    $sqlkey = "SQL Server Express Edition"
                }

                [pscustomobject]@{
                    "SQL Instance" = $server.DomainInstanceName
                    "SQL Version"  = $sqlversion
                    "SQL Edition"  = $server.Edition
                    "Product Key"  = $sqlkey
                }
            }
            $reg.Close()
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-SqlServerKey
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Alias Get-DbaSqlProductKey

        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Parameter CMSStore
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -EnableException:$false -Parameter ServersFromFile
    }
}