Reputation: 33
I'm trying to get certificates list with PowerShell
$list = Dir Cert:\LocalMachine\My | Select Issuer
I get this:
Issuer
---------
CN=*.google.com, OU=IT, O=Google, L=Texax
DC=Windows Server
CN=GOOGLE_MAIN, C=US
CN=localhost
DC=Windows Server Certificate Generator
CN=*.microsoft.com, OU=IT, O=Microsoft, L=Texas
CN=*.gmail.com, OU=IT, O=Google, L=Texax
DC=Windows Server ABC Certificate Generator
CN=*.stackoverflow.com, OU=IT, O=Google, L=Texax
DC=Windows Server XYZ Certificate Generator
CN=yahoo.com, OU=IT, O=Google, L=Texax
Then I want to take the names (from CN, ignoring DC and other), like *.google.com or *.stackoverflow.com
foreach ($cert in $list) {
$cert = $list | Select-String -Pattern 'CN\=([^,\r\n]+)'
}
But with no changes, the name still be like CN=*.google.com, OU=IT, O=Google, L=Texax
Thanks for help
Upvotes: 2
Views: 3579
Reputation: 8432
Here is an option using your regex, but not with Select-String
:
Get-ChildItem Cert:\LocalMachine\My |
ForEach-Object {
if($_.Issuer -match "CN=(?<cn>[^,\r\n]+)")
{
$matches.cn
}
}
This simply outputs a list of the CN values. If you need to use them later in your script, you can either continue with the pipeline, or capture the values somehow. For example, add them to an array:
$cnValues = @()
Get-ChildItem Cert:\LocalMachine\My |
ForEach-Object {
if($_.Issuer -match "CN=(?<cn>[^,\r\n]+)")
{
$cnValues += $matches.cn
}
}
$cnValues
You can't change the value of Issuer
on the returned objects as this is read only. If you need objects with this modified value, options include adding another property (via Add-Member) or creating your own custom object (e.g. using [PsCustomObject]
) with just the properties you need, including your calculated CN value.
Upvotes: 2
Reputation: 17161
Here's a quick example of how you might approach this for a single certificate. I'll leave the looping to you!
$certificate = Dir Cert:\LocalMachine\TrustedPublisher
$issuer = $certificate.Issuer
$parts = $issuer.Split(",")
$cn = $parts | Where-Object {$_ -like "cn*"}
Write-Host $cn
Write-Host $cn.Replace("CN=", "") -ForegroundColor Green
Upvotes: 0