functions/Restore-DbaDatabaseCertificate.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
function Restore-DbaDatabaseCertificate {
    <#
.SYNOPSIS
Imports certificates from .cer files using SMO.
 
.DESCRIPTION
Imports certificates from.cer files using SMO.
 
.PARAMETER SqlInstance
The SQL Server to create the certificates on.
 
.PARAMETER Path
The Path the contains the certificate and private key files. The path can be a directory or a specific certificate.
 
.PARAMETER SqlCredential
Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:
 
$scred = Get-Credential, this pass $scred object to the param.
 
Windows Authentication will be used if DestinationSqlCredential is not specified. To connect as a different Windows user, run PowerShell as that user.
 
.PARAMETER Password
Secure string used to decrypt the private key.
 
.PARAMETER Database
The database where the certificate imports into. Defaults to master.
 
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
 
.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command.
 
.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, Certificate
Author: Jess Pomfret (@jpomfret)
 
Website: https://dbatools.io
Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
.EXAMPLE
Restore-DbaDatabaseCertificate -SqlInstance Server1 -Path \\Server1\Certificates -password (ConvertTo-SecureString -force -AsPlainText GoodPass1234!!)
Imports all the certificates in the specified path.
 
#>

    [CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true)]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [PSCredential]$SqlCredential,
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [object[]]$Path,
        [object]$Database = "master",
        [Security.SecureString]$Password = (Read-Host "Password" -AsSecureString),
        [switch][Alias('Silent')]$EnableException
    )

    begin {

        function new-smocert ($directory, $certname) {
            if ($Pscmdlet.ShouldProcess("$cert on $SqlInstance", "Importing Certificate")) {
                $smocert = New-Object Microsoft.SqlServer.Management.Smo.Certificate
                $smocert.Name = $certname
                $smocert.Parent = $server.Databases[$Database]
                Write-Message -Level Verbose -Message "Creating Certificate: $certname"
                try {
                    $fullcertname = "$directory\$certname.cer"
                    $privatekey = "$directory\$certname.pvk"
                    Write-Message -Level Verbose -Message "Full certificate path: $fullcertname"
                    Write-Message -Level Verbose -Message "Private key: $privatekey"
                    $smocert.Create($fullcertname, 1, $privatekey, [System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password)))
                }
                catch {
                    Write-Message -Level Warning -Message $_ -ErrorRecord $_ -Target $instance
                }
            }
        }

        try {
            Write-Message -Level Verbose -Message "Connecting to $SqlInstance"
            $server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $sqlcredential
        }
        catch {
            Stop-Function -Message "Failed to connect to: $SqlInstance" -Target $SqlInstance -InnerErrorRecord $_
            return
        }
    }

    process {
        if (Test-FunctionInterrupt) { return }

        foreach ($fullname in $path) {

            if (![dbavalidate]::IsLocalhost($SqlInstance) -and !$fullname.StartsWith('\')) {
                Stop-Function -Message "Path ($fullname) must be a UNC share when SQL instance is not local." -Continue -Target $fullname
            }

            if (!(Test-DbaSqlPath -SqlInstance $server -Path $fullname)) {
                Stop-Function -Message "$SqlInstance cannot access $fullname" -Continue -Target $fullname
            }

            $item = Get-Item $fullname

            if ($item -is [System.IO.DirectoryInfo]) {
                foreach ($cert in (Get-ChildItem $fullname\* -Include *.crt, *.cer)) {
                    new-smocert -directory $fullname -certname $cert.BaseName
                }
            }
            else {
                $directory = Split-Path $fullname
                new-smocert -directory $directory -certname $item.BaseName
            }
        }
    }
}