Functions/SSL/Add-CertPFXwithLegacyCSP.ps1

Function Add-CertPFXwithLegacyCSP
    {
    Param
        (
        # Path to PFXFile
        [Parameter(Mandatory=$true)]
        [String]
        $PFXPath,
        
        # Password for Secured PFX File
        [Parameter(Mandatory=$true)]
        [String]
        $PFXPass,
        
        # Cert Store Location (CurrentUser or LocalMachine)
        [Parameter(Mandatory=$false)]
        [ValidateSet("CurrentUser","LocalMachine")]
        [String]
        $CertLocation = "LocalMachine"
        )

    DynamicParam
        {
        # Get available CSPs
        $CertStores = (Get-CertStoreInfo -Location $CertLocation)

        # Instantiate Runtime Parameter Dictionary, Attach Runtime Parameters, and return
        $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
        $RuntimeParameterDictionary.Add('CertStoreName', (New-DynamicParameter -ParamName 'CertStoreName' -ValueType string -Dataset ($CertStores.psobject.Properties.name) -Mandatory $false))
        return $RuntimeParameterDictionary
        }

    Begin
        {
        # Convert Runtime Parameter Dictionary into Available Constants
        foreach ($key in $RuntimeParameterDictionary.keys){New-Variable -Name $key -Value $RuntimeParameterDictionary.$key.value}
        
        # Select Store
        $TargetStore = $CertStores.$CertStoreName
        }

    Process
        {
        # Define Legacy CSP Option
        $Option = "AT_KEYEXCHANGE"

        # Switch on CertLocation
        $LocationMap = Switch ($Location)
            {
            "LocalMachine" {"MACHINE"}
            "CurrentUser" {"USER"}
            }
            
        # Import Certificate into selected store
        $Response = certutil -p "$PFXPass" -importpfx "$TargetStore" "$PFXPath" $Option
        if($Response[-1] -like "*CertUtil: -importPFX command completed successfully."){write-host "$($Response[0]) (with Legacy CSP)" -ForegroundColor Green}
        }
    }