Create Certificates using Powershell - 2 certificates created

Prins, Andre 126 Reputation points
2021-03-15T12:13:34.13+00:00

I have a script which generates certificates, that works, but for some reason it also generates a certificate for the OU

cls  
$url = "https://certenroll.Domain.com/certsrv/certrqma.asp"  
$servers = get-content "C:\Certificates\servers.txt"  
  
$CAName = "certenroll.Domain.com"  
$TemplateName = "operationsManagerCert"  
$E = "******@Domain.com"  
$OU = "CES"  
$O = "Company"  
$L = "Dallas"  
$S = "Texas"  
$C = "US"  
  
  
##############################################################################  
  
  
function Remove-ReqTempfiles() {  
    param(  
        [String[]]$tempfiles  
    )  
    Write-Verbose "Cleanup temp files..."  
    Remove-Item -Path $tempfiles -Force -ErrorAction SilentlyContinue  
}  
  
Function TestReq  
{  
    $Done=$False  
    Start-Sleep -Seconds 5  
    do  
    {  
        $proc = Get-Process -Name certreq -ErrorAction SilentlyContinue  
        if ($proc.count -ge 1)  
        {start-sleep -Seconds 1}  
        else  
        {$Done = $true}  
    } until ($Done)  
}  
  
  
##############################################################################  
  
$rootDSE = [System.DirectoryServices.DirectoryEntry]'LDAP://RootDSE'  
$searchBase = [System.DirectoryServices.DirectoryEntry]"LDAP://$($rootDSE.configurationNamingContext)"  
$CAs = [System.DirectoryServices.DirectorySearcher]::new($searchBase,'objectClass=pKIEnrollmentService').FindAll()  
  
if($CAs.Count -eq 4)  
{$CAName = "$($CAs[1].Properties.dnshostname)\$($CAs[1].Properties.cn)"}  
else   
{$CAName = ""}  
  
if (!$CAName -eq "")   
{$CAName = " -config `"$CAName`""}  
  
foreach ($CN in ($servers -split ("`n")))  
{  
    if ($CN.IndexOf(".") -gt 1)  
    {$FriendlyName = $CN.Substring(0,$CN.IndexOf("."))}  
    else  
    {$FriendlyName = $CN}  
  
$file = @"  
[NewRequest]  
Subject = "E=$E,CN=$CN,C=$c, S=$s, L=$l, O=$o, OU=$OU"  
MachineKeySet = TRUE  
UseExistingKeySet = False  
KeyLength = 2048  
KeySpec=1  
Exportable = TRUE  
RequestType = PKCS10  
ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"   
FriendlyName = "$FriendlyName"  
[RequestAttributes]  
CertificateTemplate = "$TemplateName"  
"@  
   
    try  
    {  
  
        $inf = [System.IO.Path]::GetTempFileName()  
        $req = [System.IO.Path]::GetTempFileName()  
        $cer = Join-Path -Path $env:TEMP -ChildPath "$CN.cer"  
  
        Set-Content -Path $inf -Value $file  
  
        Write-host "generate .req file with certreq.exe"  
        $error.Clear()  
        Start-Process "certreq" -ArgumentList "-new $inf $req" -Verb "RunAs"  
        TestReq  
  
        Write-host "certreq -submit $CAName `"$req`" `"$cer`""  
        Start-Process "certreq" -ArgumentList "-submit $CAName $req $cer" -Verb "RunAs"  
        TestReq  
  
        Write-host "request was successful. Result was saved to $cer"  
  
        write-host "retrieve and install the certificate"  
        Start-Process "certreq" -ArgumentList "-accept $cer -machine" -Verb "RunAs"  
        TestReq  
  
        write-host "Done, cleaning up temp files"  
        Remove-ReqTempfiles -tempfiles $inf, $req, $cer  
  
    }  
    catch  
    {  
        write-host "Error during request"  
        $error  
    }  
}  

Result:
77735-untitled.png

as you can see at the start of the program, OU="CES" and later in my local machine certificates, I see the CES certificate...
I can see that the Subject of the CES certificate is the same and it is created also with the OperationsManagerCert template...

I just cannot figure out how/why a CES certificate is created and not only the $CN
in servers.txt I have 4 server FQDN names, one per line. and if I just let the script run, it also creates 4x a CES certificate.??!!!??

this is the $inf file:
[NewRequest]
Subject = "E=andre.prins@keyman .com,CN=ui1pawb921,C=US, S=Texas, L=Dallas, O=Company, OU=CES"
MachineKeySet = TRUE
UseExistingKeySet = False
KeyLength = 2048
KeySpec=1
Exportable = TRUE
RequestType = PKCS10
ProviderName = "Microsoft Enhanced Cryptographic Provider v1.0"
FriendlyName = "ui1pawb921"
[RequestAttributes]
CertificateTemplate = "operationsManagerCert"

(I checked - when I create the certificates manually, OU is also "only" showing CES)

the $req file looks good to me (I deleted most lines to save space )
get-content $req

-----BEGIN NEW CERTIFICATE REQUEST-----
MIIFTDCCBDQCAQAwgacxDDAKBgNVBAsMA0NFUzEVMBMGA1UECgwMQmFrZXIgSHVn
cOG8CqpIzZ42EPgMVZPksQ==
-----END NEW CERTIFICATE REQUEST-----

And I checked the $cer file too
get-content $cer

-----BEGIN CERTIFICATE-----
MIIHQzCCBSugAwIBAgIKG1gOKQAAAAAMATANBgkqhkiG9w0BAQsFADBhMRMwEQYK
RhER3xBDiVTQ/Hq16Rw5LcTpjrqfkIqriEkoDrHeKy3dT2EKNuBk
-----END CERTIFICATE-----

System Center Operations Manager
System Center Operations Manager
A family of System Center products that provide infrastructure monitoring, help ensure the predictable performance and availability of vital applications, and offer comprehensive monitoring for datacenters and cloud, both private and public.
1,602 questions
Windows for business Windows Server User experience PowerShell
{count} votes

2 answers

Sort by: Most helpful
  1. Prins, Andre 126 Reputation points
    2021-03-16T10:08:06.95+00:00

    ahhh sometimes the most obvious is overlooked.....

    sorry my bad - it turns out the result of the split is adding empty lines, and that is causing the unwanted certificate
    I put in a simple check if ($CN -eq "") {continue} and that skips the blank lines.


  2. Prins, Andre 126 Reputation points
    2021-03-17T08:35:07.537+00:00

    thanks for your response,
    but I added the split because it was not behaving as I expected.
    but you are right, without the split works fine too - that's how I started, but I was stepping thru manually in debug and noticed the 2nd loop was blank, so I assumed it was the last line, and assumed it was treating the lines with text as one string... jumping to conclusions too quick....

    I later looked at it via Notepad++ and then it revealed the extra linefeeds
    see below the result in notepad++ and the "normal" notepad - which why I did not notice the extra lines initially.
    78731-image.png

    after removing the extra empty lines in notepad++ it worked fine without the split.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.