Skip to content

Instantly share code, notes, and snippets.

@duffney
Last active July 15, 2016 11:06
Show Gist options
  • Save duffney/7522ec3edd561e916d06 to your computer and use it in GitHub Desktop.
Save duffney/7522ec3edd561e916d06 to your computer and use it in GitHub Desktop.
Export-MachineCert
Function Export-MachineCert {
<#
.SYNOPSIS
Harvests a certificate from a remote system.
.DESCRIPTION
Invokes a command on a remote system to copy the certificate to the machine running the command.
.PARAMETER Computername
Specifies the name of the remote system to harvest the certificate.
.PARAMETER Path
Provides the path where the certificate is copied to on the host system.
.PARAMETER Template
Specifies the template used when generating the certificate on the remote system.
.EXAMPLE
Export-MachineCert -computername S3 -Path C:\Certs
.Notes
Requires PowerShell version 4
Original Author:Jeff Hicks
Editor: Josh Duffney
#>
[cmdletbinding()]
Param(
[ValidateNotNullorEmpty()]
[string]$computername,
[ValidateScript({Test-Path $_})]
[string]$Path="$env:SystemDrive\Certs",
[ValidateSet("Client Authentication","Server Authentication")]
[string]$Template
)
Try {
#assumes a single certificate so sort on NotAfter
Write-Verbose "Querying $computername for Machine certificates"
$cert = invoke-command {
Param($template)
Get-ChildItem Cert:\LocalMachine\my |
Where-Object {$_.EnhancedKeyUsageList.FriendlyName -contains $Template -AND $_.notAfter -gt (Get-Date) } |
Sort-Object NotAfter -Descending | Select -first 1
Write-Host $Template
} -computername $computername -ErrorAction Stop -ArgumentList $Template
write-verbose ($cert | out-string)
}
Catch {
Throw $_
}
if ($cert) {
#verify and export
if (Test-Certificate $cert) {
$exportPath = Join-path -Path $Path -ChildPath "$computername.cer"
Write-Verbose "Exporting certificate for $($cert.subject.trim()) to $exportpath"
[pscustomobject]@{
Computername = $cert.Subject.Substring(3)
Thumbprint = $cert.Thumbprint
Path = Export-Certificate -Cert $cert -FilePath $exportPath
}
} #if Test OK $cert
else {
Write-Warning "Failed to verify or find a certificate"
}
} #if $cert
} #Export-MachineCert
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment