Public/New-SelfSignedCert.ps1


#Requires -RunAsAdministrator

function New-SelfSignedCert {
    [CmdletBinding(SupportsShouldProcess = $true)]
    param(
        [Parameter(Mandatory = $true)]
        [string] $FriendlyName,
        [Parameter(Mandatory = $true)]
        [string] $DnsName,
        [Parameter(Mandatory = $true)]
        [string] $CertStoreLocation
    )

# Generate a cert
    # https://docs.microsoft.com/en-us/powershell/module/pkiclient/new-selfsignedcertificate?view=win10-ps
    $cert = New-SelfSignedCertificate -FriendlyName $FriendlyName -DnsName $DnsName -CertStoreLocation $CertStoreLocation -NotAfter (Get-Date).AddYears(10) -Verbose
    $certStoreParent = Split-Path -Path $CertStoreLocation -Parent
    $certStoreName = Split-Path $certStoreParent -Leaf
    # Trust the cert
    # https://stackoverflow.com/questions/8815145/how-to-trust-a-certificate-in-windows-powershell
    $store = New-Object System.Security.Cryptography.X509Certificates.X509Store 'Root',$certStoreName
    $store.Open("ReadWrite")
    $store.Add($cert)
    $store.Close()

    # remove the untrusted copy of the cert
    #$cert | Remove-Item

    Write-Verbose "Created certificate $FriendlyName with thumbprint $($cert.Thumbprint)"

    return $cert
}