Powershell script to request and export Certificates with Private Key (PFX)

Other one I have taken from my old Blog site “https://vipinvasudevan.blogspot.com/”

Situation is, Our organization decided to implement a solution to implement certificate level authentication for a system used in-house  We have had almost around 2000+ roaming laptop users who never connect to intranet but need certificate to be downloaded. We have no option left but to create an offline request for them on behalf and send across to them for installing it.
Here is the solution I found to request for computer certificate using list of computers in text (Compt.txt)
—————————– SCRPT START HERE ————————————————–
$import= “C:\Users\USER\Desktop\Comp.txt”
get-content $import |foreach{
$comp= $_
$comp1 =”CN=”+$comp+”.DOMAIN.com”
$d = ‘”USTComputers”‘
$b = “[NewRequest]
$path = “C:\Users\USER\Desktop\”+$comp+”.inf”
$pat = “C:\Users\USER\Desktop\”+$comp+”_.inf”
$path1 = “C:\Users\USER\Desktop\”+$comp+”.req”
$path2 = “C:\Users\USER\Desktop\”+$comp+”.cer”
$path3 = “C:\Users\USER\Desktop\”+$comp+”.log”
$cername = “Cert”+$comp+”.cer”
clear-content $path -force
add-content $pat $b
$aa = get-content $pat
$bb = $aa -replace ‘CN’,'”CN’
$cc = $bb -replace ‘DOMAIN.com’,’DOMAIN.com”‘
clear-content $pat -force
add-content $path $cc
certreq -new $path $path1
certreq -submit -config “CASERVER\CANAME” $path1 $path2 |out-file $path3
$certid = Get-content $path3 |Select-String -Pattern ‘Requestid: “‘
$certid = $certid -replace ‘Requestid: “‘ -replace ‘”‘
certreq -retrieve -f -config “CASERVER.DOMAIN.com\CANAME” $certid $cername
certreq –accept $cername
—————————– SCRPT END HERE ————————————————–
This will download all required certificate in to requester computer store, Now we need to export these certificate with private key (in PFX format) and share it with external user
—————————– SCRPT START HERE ————————————————–
cd cert:
cd localmachine
cd my
Get-ChildItem |select Thumbprint,Subject | Export-Csv C:\temp\certificate.csv -NoTypeInformation
$import= import-csv “C:\temp\certificate.csv”
foreach($line in $import)
$thumb = $line.Thumbprint
$sub = $line.Subject
$subj = $sub -replace “.domain.com”
$subje = $subj -replace “CN=”
$FilePath = “C:\temp\”+$subje+”.pfx”
certutil -exportPFX -p “Password” my $thumb $FilePath
—————————– SCRPT END HERE ————————————————–
Copy and paste both script in notepad and save as ‘Filename.PS1’ and execute on need basis. Make sure that you have set your execution policy to execute this Script.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s