functions/Export-DbaCredential.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
function Export-DbaCredential {
    <#
    .SYNOPSIS
        Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.
 
    .DESCRIPTION
        Exports credentials INCLUDING PASSWORDS, unless specified otherwise, to sql file.
 
        Requires remote Windows access if exporting the password.
 
    .PARAMETER SqlInstance
        The target SQL Server instance or instances.
 
    .PARAMETER SqlCredential
        Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
    .PARAMETER Credential
        Login to the target OS using alternative credentials. Accepts credential objects (Get-Credential)
 
    .PARAMETER Path
        The path to the directory that will contain the exported sql file.
 
    .PARAMETER FilePath
       The specific path to a file which will contain the output.
 
    .PARAMETER Identity
        The credentials to export. If unspecified, all credentials will be exported.
 
    .PARAMETER InputObject
        Allow credentials to be piped in from Get-DbaCredential
 
    .PARAMETER ExcludePassword
        Exports the SQL credential without any sensitive information.
 
    .PARAMETER Append
        Append to Path
 
    .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: Credential
        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
 
    .EXAMPLE
        PS C:\> Export-DbaCredential -SqlInstance sql2017 -Path C:\temp\cred.sql
 
        Exports credentials, including passwords, from sql2017 to the file C:\temp\cred.sql
 
    #>

    [CmdletBinding()]
    param (
        [DbaInstanceParameter[]]$SqlInstance,
        [string[]]$Identity,
        [PSCredential]$SqlCredential,
        [PSCredential]$Credential,
        [string]$Path = (Get-DbatoolsConfigValue -FullName 'Path.DbatoolsExport'),
        [Alias("OutFile", "FileName")]
        [string]$FilePath,
        [switch]$ExcludePassword,
        [switch]$Append,
        [Parameter(ValueFromPipeline)]
        [Microsoft.SqlServer.Management.Smo.Credential[]]$InputObject,
        [switch]$EnableException
    )
    begin {
        $null = Test-ExportDirectory -Path $Path
        $serverArray = @()
        $credentialArray = @{}
        $credentialCollection = New-Object System.Collections.ArrayList
    }
    process {
        if (Test-FunctionInterrupt) { return }

        if (-not $InputObject -and -not $SqlInstance) {
            Stop-Function -Message "You must pipe in a Credential or specify a SqlInstance"
            return
        }

        if (Test-Bound -ParameterName SqlInstance) {
            foreach ($instance in $SqlInstance) {
                try {
                    $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential -MinimumVersion 9

                    $serverCreds = $server.Credentials
                    if (Test-Bound -ParameterName Identity) {
                        $serverCreds = $serverCreds | Where-Object Identity -in $Identity
                    }

                    $InputObject += $serverCreds
                } catch {
                    Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
                }
            }
        }

        foreach ($input in $InputObject) {
            $server = $input.Parent
            $instance = $server.Name

            if ($serverArray -notcontains $instance) {
                try {
                    if ($ExcludePassword) {
                        $serverCreds = $server.Credentials
                        $creds = New-Object System.Collections.ArrayList

                        foreach ($cred in $server.Credentials) {
                            $credObject = [PSCustomObject]@{
                                Name     = '[' + $cred.name + ']'
                                Identity = $cred.Id.ToString()
                                Password = ''
                            }
                            $creds.Add($credObject) | Out-Null
                        }
                        $creds | Add-Member -MemberType NoteProperty -Name 'SqlInstance' -Value $instance
                        $creds | Add-Member -MemberType NoteProperty -Name 'ExcludePassword' -Value $ExcludePassword
                        $credentialCollection.Add($credObject) | Out-Null
                    } else {
                        if (-not (Test-SqlSa -SqlInstance $server)) {
                            Stop-Function -Message "Not a sysadmin on $instance. Quitting." -Target $instance -Continue
                        }

                        Write-Message -Level Verbose -Message "Getting NetBios name for $instance."
                        $sourceNetBios = Resolve-NetBiosName $server

                        Write-Message -Level Verbose -Message "Checking if Remote Registry is enabled on $instance."
                        try {
                            Invoke-Command2 -Raw -Credential $Credential -ComputerName $sourceNetBios -ScriptBlock { Get-ItemProperty -Path "HKLM:\SOFTWARE\" } -ErrorAction Stop
                        } catch {
                            Stop-Function -Message "Can't connect to registry on $instance." -Target $sourceNetBios -ErrorRecord $_
                            return
                        }

                        $creds = Get-DecryptedObject -SqlInstance $server -Type Credential
                        Write-Message -Level Verbose -Message "Adding Members"
                        $creds | Add-Member -MemberType NoteProperty -Name 'SqlInstance' -Value $instance
                        $creds | Add-Member -MemberType NoteProperty -Name 'ExcludePassword' -Value $ExcludePassword
                        $credentialCollection.Add($creds) | Out-Null
                    }
                } catch {
                    Stop-Function -Continue -Message "Failure" -ErrorRecord $_
                }

                $serverArray += $instance

                $key = $input.Parent.Name + '::[' + $input.Name + ']'
                $credentialArray.add( $key, $true )
            } else {
                $key = $input.Parent.Name + '::[' + $input.Name + ']'
                $credentialArray.add( $key, $true )
            }
        }
    }

    end {
        $sql = @()
        foreach ($cred in $credentialCollection) {
            Write-Message -Level Verbose -Message "Credentials in object = $($cred.Count)"

            foreach ($currentCred in $creds) {
                $FilePath = Get-ExportFilePath -Path $PSBoundParameters.Path -FilePath $PSBoundParameters.FilePath -ServerName $currentCred.SqlInstance -Type Sql

                $key = $currentCred.SqlInstance + '::' + $currentCred.Name
                if ( $credentialArray.ContainsKey($key) ) {
                    $name = $currentCred.Name.Replace("'", "''")
                    $identity = $currentCred.Identity.Replace("'", "''")
                    if ($currentCred.ExcludePassword) {
                        $sql += "CREATE CREDENTIAL $name WITH IDENTITY = N'$identity', SECRET = N'<EnterStrongPasswordHere>'"
                    } else {
                        $password = $currentCred.Password.Replace("'", "''")
                        $sql += "CREATE CREDENTIAL $name WITH IDENTITY = N'$identity', SECRET = N'$password'"
                    }

                    Write-Message -Level Verbose -Message "Created Script for $name"
                }
            }

            try {
                if ($Append) {
                    Add-Content -Path $FilePath -Value $sql
                } else {
                    Set-Content -Path $FilePath -Value $sql
                }
            } catch {
                Stop-Function -Message "Can't write to $FilePath" -ErrorRecord $_ -Continue
            }
            Get-ChildItem -Path $FilePath
            Write-Message -Level Verbose -Message "Credentials exported to $FilePath"
        }
    }
}