Public/Get-PfxCertificateBetter.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<#
    .SYNOPSIS
        Adds -Password parameter to the existing Get-PFXCertificate cmdlet in order to avoid prompt in the event
        that a password is needed.
 
    .DESCRIPTION
        See .SYNOPSIS
 
    .NOTES
 
    .PARAMETER FilePath
        This parameter is MANDATORY.
 
    .PARAMETER LiteralPath
        This parameter is MANDATORY.
 
    .PARAMETER Password
        This parameter is OPTIONAL.
 
    .PARAMETER x509KeyStorageFlag
        This parameter is OPTIONAL (however, it has a default value of 'DefaultKeySet')
 
    .EXAMPLE
        # Import the MiniLab Module and -
 
        PS C:\Users\zeroadmin> Get-PfxCertificateBetter -Password "PlainTextPwd" -FilePath "$HOME\test.pfx"
 
#>

function Get-PfxCertificateBetter {
    [CmdletBinding(DefaultParameterSetName='ByPath')]
    param(
        [Parameter(Position=0, Mandatory=$true, ParameterSetName='ByPath')]
        [string[]]$FilePath,

        [Parameter(Mandatory=$true, ParameterSetName='ByLiteralPath')]
        [string[]]$LiteralPath,

        [Parameter(Position=1, ParameterSetName='ByPath')] 
        [Parameter(Position=1, ParameterSetName='ByLiteralPath')]
        [string]$Password,

        [Parameter(Position=2, ParameterSetName='ByPath')]
        [Parameter(Position=2, ParameterSetName='ByLiteralPath')] 
        [ValidateSet('DefaultKeySet','Exportable','MachineKeySet','PersistKeySet','UserKeySet','UserProtected')]
        [string]$x509KeyStorageFlag = 'DefaultKeySet'
    )

    if($PsCmdlet.ParameterSetName -eq 'ByPath'){
        $literalPath = Resolve-Path $filePath 
    }

    if(!$Password){
        # if the password parameter isn't present, just use the original cmdlet
        $cert = Get-PfxCertificate -LiteralPath $literalPath
    } else {
        # otherwise use the .NET implementation
        $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
        $cert.Import($literalPath, $Password, $X509KeyStorageFlag)
    }

    return $cert
}