Copy-CertificateToRemote.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
<#
    .SYNOPSIS
        Copies a certificate with its chain to the store of a remote computer
 
    .DESCRIPTION
        Copies a certificate with its chain to the store of a remote computer
 
    .PARAMETER Certificate
        The certificate to copy
 
    .PARAMETER MoveChain
        The password to use when exporting certificates with private key
 
    .PARAMETER ComputerName
        Target computer
 
    .PARAMETER Credential
        Target Credential
 
    .PARAMETER Session
        Target session
 
    .EXAMPLE
        $certificate=New-DomainSignedCertificate -Hostname "example.com" -CertificateAuthority ""
        $pfxPassword=ConvertTo-SecureString “password” -AsPlainText -Force
        $certificate|Copy-CertificateToRemote -ComputerName EXAMPLE -PfxPassword $pfxPassword -MoveChain
 
    .LINK
        New-DomainSignedCertificate
 
    .LINK
        Move-CertificateToRemote
#>

function Copy-CertificateToRemote {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Computer")]
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ParameterSetName="Session")]
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $Certificate,
        [Parameter(Mandatory=$false,ParameterSetName="Computer")]
        [Parameter(Mandatory=$false,ParameterSetName="Session")]
        [securestring]$PfxPassword=$null,
        [Parameter(Mandatory=$false,ParameterSetName="Computer")]
        [Parameter(Mandatory=$false,ParameterSetName="Session")]
        [switch]$MoveChain=$false,
        [Parameter(Mandatory=$true,ParameterSetName="Computer")]
        [AllowNull()]
        $ComputerName=$null,
        [Parameter(Mandatory=$false,ParameterSetName="Computer")]
        [pscredential]$Credential=$null,
        [Parameter(Mandatory=$true,ParameterSetName="Session")]
        [AllowNull()]
        $Session
    )

    try {
        if($Certificate.HasPrivateKey)
        {
            if(-not $PfxPassword)
            {
                throw "Parameter PfxPassword is required to move a certificate with private key"
            }
        }

        $identifier=$Certificate.Thumbprint
        #Export certificate to temp
        $exportPath=Join-Path $env:TEMP $identifier
        if(Test-Path $exportPath)
        {
            Remove-Item $exportPath -Recurse -Force
        }
        New-Item $exportPath -ItemType Directory|Out-Null
        [int]$iteration=1
        if($Certificate.HasPrivateKey)
        {
            $pfxPath=Join-Path $exportPath "$("{0:00}" -f $iteration).$($Certificate.Thumbprint).pfx"
            $Certificate |Export-PfxCertificate -FilePath $pfxPath -ChainOption BuildChain -Password $PfxPassword|Out-Null
        }
        else
        {
            $cerPath=Join-Path $exportPath "$("{0:00}" -f $iteration).$($Certificate.Thumbprint).cer"
            $Certificate |Export-Certificate -FilePath $cerPath -ChainOption BuildChain -Password $pfxPassword|Out-Null
        }

        if($MoveChain)
        {
            $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
            if($chain.Build($Certificate))
            {
                $chain.ChainElements|Select-Object -ExpandProperty Certificate -Skip 1|ForEach-Object {
                    $iteration++
                    $cerPath=Join-Path $exportPath "$("{0:00}" -f $iteration).$($_.Thumbprint).cer"
                    $_|Export-Certificate -FilePath $cerPath|Out-Null
                }
            }
        }

        if($ComputerName)
        {
            if($Credential)
            {
                $Session=New-PSSession -ComputerName $ComputerName -Credential $Credential
            }
            else
            {
                $Session=New-PSSession -ComputerName $ComputerName
            }
        }

        #Copy certificate to remote temp directory
        $prepareDirectoryBlock = {
            $importPath=Join-Path $env:TEMP $Using:identifier
            if(Test-Path $importPath)
            {
                $null=Remove-Item $importPath -Recurse -Force
            }
            (New-Item $importPath -ItemType Directory).FullName
        }
        $importAbsolutePathOnRemote=Invoke-Command -Session $Session -ScriptBlock $prepareDirectoryBlock -HideComputerName
        Copy-Item -Path "$exportPath\*.*" -Destination $importAbsolutePathOnRemote -ToSession $session -Force|Out-Null

        #Import certificate on remote
        $importBlock= {
            $importPath=$Using:importAbsolutePathOnRemote
            try 
            {
                Get-ChildItem -Path $importPath | Sort-Object -Property Name | ForEach-Object {
                    $item=$_
                    switch ($item.Extension)
                    {
                        '.pfx' {
                            Import-PfxCertificate -FilePath $item.FullName -CertStoreLocation  "cert:\localMachine\my" -Password ($Using:PfxPassword) -Exportable | Out-Null
                        }
                        '.cer' {
                            if($item.Name.StartsWith("01"))
                            {
                                Import-Certificate -FilePath $item.FullName -CertStoreLocation "cert:\localMachine\my" | Out-Null
                            }
                            else
                            {
                                Import-Certificate -FilePath $item.FullName -CertStoreLocation "cert:\localMachine\root" | Out-Null
                            }
                        }
                    }
                }
            }
            finally
            {
                if(Test-Path $importPath)
                {
                    Remove-Item $importPath -Recurse -Force
                }
            }
        }

        Invoke-Command -Session $session -ScriptBlock $importBlock

    }
    finally
    {
        if($exportPath -and (Test-Path $exportPath))
        {
            Remove-Item $exportPath -Recurse -Force
        }
        if($ComputerName -and $Session)
        {
            $Session|Remove-PSSession
        }
    }


}