functions/Get-DscEncryptionCertificate.ps1

<#
.SYNOPSIS
Exports Certificate from target server
 
.DESCRIPTION
This process connects to a session and gets a certificate for document encyption.
 
In the case the certificate is available the certificate is simply exported.
If the certificate does not exist (based on naming convention in the process), the process will create the certificate
 
Only creates and exports on Windows 10 / Server 2016.
For other versions of Windows, the certificate must be created and exported manually, then this script will still pick it up.
Manual exports should be named: FQDNsuffix.cer and stored in c:\temp
e.g. c:\temp\ServerNameDscEncryptionCert.cer
 
.PARAMETER WorkingDirectory
base location / where should the certificate be exported to locally
 
.PARAMETER Sessions
Array of sessions to connect to
 
.PARAMETER Suffix
Anything you might want to add to the file name
 
.EXAMPLE
Get-DscEncryptionCertificate -WorkingDirectory $ReleaseDirectory -Sessions $Sessions -Suffix "-DscEncryptionCert"
 
#>

function Get-DscEncryptionCertificate {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [String]
        $WorkingDirectory,
        [Parameter(Mandatory=$true)]
        [System.Management.Automation.Runspaces.PSSession[]]
        $Sessions,
        [String]
        $Suffix="DscEncryptionCert"
    )
    
    begin {
    }
    
    process {
        Invoke-Command -Session $Sessions -ScriptBlock {
            Param($Suffix)
        
            if ( [Environment]::OSVersion.Version -ge (new-object 'Version' 10, 0)) {
                $FQDN = ([System.Net.Dns]::GetHostByName($env:computerName).HostName)
                $DnsName = "$FQDN$Suffix"
    
                # note: These steps need to be performed in an Administrator PowerShell session
                if ($null -ne (Get-ChildItem -Path cert:\LocalMachine\My | Where-Object Subject -Like CN=$DnsName)) {
                    $thumbprint = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object Subject -Like CN=$DnsName | Select-Object -ExpandProperty ThumbPrint
                    $cert = "cert:\LocalMachine\My\$thumbprint"
                }
                else {
                    $cert = New-SelfSignedCertificate -Type DocumentEncryptionCertLegacyCsp -DnsName $DnsName -HashAlgorithm SHA256
                }
    
                Export-Certificate -Cert $cert -FilePath "c:\temp\$($DnsName).cer"
            } 
            
        } -ArgumentList $Suffix
            
        foreach ($session in $Sessions) {
            $cn = $session.ComputerName
            Copy-Item -FromSession $Session -Path "c:\temp\$($cn)$($Suffix).cer" -Destination $workingDirectory
        }
    }
    
    end {
    }
}