powershellfor-loopcertificateexport-to-csvwindows-server-2019

How do I list certificates in personal store across all servers in domain


I need to get a list of all of the certificates in the personal store across all of the servers in my domain. I am currently using the following powershell command which provides the desired results

Get-ChildItem Cert:\localmachine\my | Export-Csv \\filepath\filename.csv

However this requires me to go into each server and run the command. how do I avoid doing so? I used the following to create a csv file aof all of the server names to iterate through

get-adcomputer -filter * -SearchBase $OUpath | Select-object name | export-csv -NoType $ExportPath

all of the servers are in a specific OU which is the value of the %OUPath variable.

Here is the script I have tried, however it does not give me the certificate data I am looking for.

$OUpath = 'OU=Servers,OU=someOU,DC=somedomain,DC=com'
$ExportPath = '\\filepath\ServerList.csv'
get-adcomputer -filter * -SearchBase $OUpath | Select-object name | export-csv -NoType $ExportPath

import-csv $exportpath
foreach-object{
    Get-ChildItem Cert:\localmachine\my | Export-Csv -append -path \\filepath\certlist.csv
    }

there are over 500 servers in the OU yet the file only has 30 rows, and is missing pertinent information regarding the cert for each server. I am looking for the following headers DnsNameList FriendlyName NotAfter NotBefore HasPrivateKey Issuer


Solution

  • Here is the final code that produced the desired results

    $OUpath = 'OU=Servers,OU=someOU,DC=somedomain,DC=com'
    $command = {Get-ChildItem Cert:\localmachine\My | select friendlyname, dnsnamelist, NotAfter, NotBefore, thumbprint, Issuer, Subject, HasPrivateKey | Format-Table -groupby dnsnamelist -autosize }
    $list = Get-ADComputer -filter * -SearchBase $OUpath | select-object -expand name                                     #Creates a list of servers from the Servers AD OU
    ForEach($name in $list)  #Loops through each name in the list, pulls the Certificate information, and appends it to a .csv file
    {
       if ($name -NotLike 'SomeServerName')
          {
            $s = New-PSSession -ComputerName $name
            invoke-command -Session $s -ScriptBlock $command -AsJob
            $job = Get-Job
            $job|Receive-Job -Keep > \\SomeOutputFile.csv         #Gets the output of the remote job,and exports to a .csv file
           }
    {
    get-job | remove-job    #Cleans up all jobs created by script
    get-PSSession | remove-PSSession    #cleans up all remote sessions created by script