Tuesday, September 12, 2017

Powershell: Generate CSR

Wrote this function to generate SAN certificate requests. This isn't a robust solution, nor does it follow best practice, it is more of a hey it works with a Microsoft CA.


 #https://social.technet.microsoft.com/Forums/Lync/en-US/b4e27454-c60f-4346-9f7d-22214f49ab6f/create-inf-file-to-create-req-using-certreqexe?forum=winserversecurity

Found a more correct script after i wrote this here https://pscsr256.codeplex.com/

<#
.Synopsis
   Generate CSR by Tony Unger
.DESCRIPTION
   Generates CSR
.EXAMPLE
   new-csr -CommonName "test0.microsoft.com" -DNSNames $HostNames
.EXAMPLE
   new-csr -CommonName "test0.microsoft.com"
#>
function new-csr
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        # Common name for request
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $CommonName,

        # SAN DNS names
        [string[]]
        $DNSNames
    )

    Begin
    {
    $Date = (Get-Date).ToString('ddMMyyyy')
    $ReqFile = "Cert_Req-$CommonName-" + "$Date" + ".csr"
    }
    Process
    {
        $InfFile = @"
        [NewRequest]`r
        Subject = "CN=$CommonName"`r
        KeySpec = 1
        KeyLength = 2048
        Exportable = TRUE`r
        RequestType = CMC`r
        [Extensions] 
        2.5.29.17 = "{text}" 
        _continue_ = "dns=$CommonName&"`n
"@
    foreach ($DNSName in $DNSNames){
        $InfFile =$InfFile + @" 
            _continue_ = "dns=$DNSName&"`n
"@


    }
    $InfFile
        $FinalInfFile = "Cert_Req_Inf-$CommonName-" + "$Date" + ".inf"
        New-Item $FinalInfFile -type file -value $InfFile -Force

        cmd /c "certreq -new $FinalInfFile $ReqFile"
    }
    End
    {
    }
}

$Hostnames = "test1.microsoft.com","test2.microsoft.com"
new-csr -CommonName "test0.microsoft.com" -DNSNames $HostNames

No comments:

Post a Comment