Export-AzureAutomationRunasCertificate.ps1

<#PSScriptInfo
 
.VERSION 1.0
 
.GUID 364ddb0d-7134-447b-b54f-f56ccaaa41ee
 
.AUTHOR chris.speers@avanade.com
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS AzureAutomation,PFX,AzureRunAsConnection
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES Orchestrator.AssetManagement.Cmdlets
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>
 

#Requires -Module AzureRM.profile
#Requires -Module AzureRM.Storage

<#
 
.DESCRIPTION
 Exports an Azure Automation Runas Certificate to a BLOB container
 
#>
 
[CmdletBinding()]
param
(    
    [Parameter(Mandatory=$false)]
    [String]
    $ConnectionName ="AzureRunAsConnection",
    [Parameter(Mandatory=$false)]
    [String]    
    $CertThumbprint,    
    [Parameter(Mandatory=$false)]
    [String]    
    $PfxPassword="Password1",
    [Parameter(Mandatory=$true)]
    [String]
    $ResourceGroup,
    [Parameter(Mandatory=$true)]
    [String]
    $StorageAccountName,
    [Parameter(Mandatory=$false)]
    [String]    
    $BlobContainer="runascerts"
)
try
{
    $ContainerName=$BlobContainer.ToLower()
    
    $ServicePrincipalConnection=Get-AutomationConnection -Name $ConnectionName
    $ArmAccount=Add-AzureRmAccount `
        -ServicePrincipal `
        -TenantId $ServicePrincipalConnection.TenantId `
        -ApplicationId $ServicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint
    if([String]::IsNullOrEmpty($CertThumbprint))
    {
        $CertThumbprint=$ServicePrincipalConnection.CertificateThumbprint
    }        
    $StorageAccount= Get-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $ResourceGroup -ErrorAction Stop
    $ContainerExists=$false
    try
    {
        $Container=Get-AzureStorageContainer -Context $StorageAccount.Context -Name $ContainerName -ErrorAction Stop
        $ContainerExists=$true
    }
    catch {
        $ContainerExists=$false
    }
    if($ContainerExists -eq $false)
    {
        Write-Verbose "Container $BlobContainer does not exist. Creating..."
        $Container=New-AzureStorageContainer -Context $StorageAccount.Context -Name $ContainerName|Out-Null          
    }  
    Write-Verbose "Exporting Certificate with thumbprint $CertThumbprint to $($StorageAccount.Context.BlobEndPoint)"
    $RunAsCert=Get-ChildItem Cert:\CurrentUser\My | Where-Object Thumbprint -eq $CertThumbprint | Select-Object -First 1
    if($RunAsCert -ne $null)
    {
        Write-Verbose "Exporting $($RunAsCert.Subject) to $StorageAccountName"
        $CertBytes=$RunAsCert.Export('pfx',$PfxPassword)
        $CertString=[System.Convert]::ToBase64String($CertBytes)
        $FilePath=Join-Path $env:TEMP "$($RunAsCert.Subject).pfx"
        $CertBytes|Set-Content -Path $FilePath -Force -Encoding Byte
        Write-Verbose "Uploading $FilePath => $($StorageAccount.Context.BlobEndPoint)/$ContainerName"
        $PfxBlob=Set-AzureStorageBlobContent -Container $ContainerName -Context $StorageAccount.Context -File $FilePath -Force
        Write-Output @{
            Base64=$CertString;
            PfxUri=$PfxBlob.ICloudBlob.Uri;
        }        
    }
    else
    {
        throw "Unable to find a certificate with the thumbprint $CertThumprint"
    }
}
catch
{
    if (!$servicePrincipalConnection)
    {
        Write-Error "Connection $ConnectionName not found."
        throw "Connection $ConnectionName not found."
    } else{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}