ps/Modules/Alkami.Ops.Certificates/Scripts/ExportRemoteCertificates.ps1
2023-05-30 22:51:22 -07:00

85 lines
2.6 KiB
PowerShell

param(
$serverString,
$exportPassword,
$importPath
)
$servers = $serverString.Split(",");
$exportCertificateZipPath = "C:/temp/certificateExport.zip";
$script = {
$password = $using:exportPassword;
$exportPath = $using:exportCertificateZipPath;
# Create the cert temp cert export directory for each server.
$tempPath = "C:/temp/certificateExport";
if(Test-Path $tempPath)
{
Remove-Item -Path $tempPath -Recurse -Force;
}
New-Item -Path $tempPath -ItemType Directory;
# Export all certificates and compress them.
try {
Write-Host "Exporting Certificates to $tempPath";
Export-Certificates -exportPassword $password -exportPath $tempPath;
$zipPath = "$tempPath/*";
Write-Host "Zipping certificates at $zipPath to archive $exportPath";
Compress-Archive -Path $zipPath -DestinationPath $exportPath -Force | Out-Null;
}
catch {
throw $_;
}
finally {
# Clean up exported certs.
if(Test-Path $tempPath)
{
Remove-Item -Path $tempPath -Recurse -Force;
}
}
}
try
{
# Export all of the certificates on each server.
Invoke-Command -ComputerName $servers -ScriptBlock $script;
# Read all of the certificates back to the agent machine and unzip.
$copyToAgentScript = {
param($server)
$certZipPath = Get-UncPath -filePath $using:exportCertificateZipPath -ComputerName $server;
$serverImportDirectory = (Join-Path $using:importPath $server);
$serverImportFile = (Join-Path $serverImportDirectory "certs.zip");
if(Test-Path $certZipPath)
{
if(!(Test-Path $serverImportDirectory))
{
New-Item -Path $serverImportDirectory -ItemType Directory | Out-Null;
}
Write-Host "Copying $certZipPath to $serverImportFile";
Move-Item -Path $certZipPath -Destination $serverImportFile -Force | Out-Null;
Write-Host "Expanding archive $serverImportfile in $serverImportDirectory"
Expand-Archive -Path $serverImportFile -DestinationPath $serverImportDirectory -Force;
Remove-Item -Path $serverImportFile -Force;
}
}
Invoke-Parallel -objects $servers -script $copyToAgentScript;
}
finally
{
# Clean up the certificate export zip's on all of the servers if the process crashed.
foreach($server in $servers)
{
$certZipPath = Get-UncPath -filePath $exportCertificateZipPath -ComputerName $server;
if(Test-Path $certZipPath)
{
Write-Host "Cleaning up $certZipPath";
Remove-Item -Path $certZipPath;
}
}
}