- 15 minutes to read

FAQ - Duplicate Certificate Detection

Overview

Duplicate certificates represent a critical inventory and security management problem. This page explains why Nodinite monitors for duplicate certificates, how to detect them, and what actions to take.

  • ✅ Identifies multiple certificates with identical Subject/SAN combinations
  • ✅ Detects high-risk scenarios where duplicates have private keys
  • ✅ Monitors for duplicates across certificate stores
  • ✅ Prevents application confusion and certificate selection errors

Understanding Duplicate Certificates

Nodinite identifies duplicate certificates by matching the Subject Name and Subject Alternative Names (SAN) across all monitored certificate stores. Two certificates with identical Subject/SAN but different thumbprints are flagged as duplicates.

Why Duplicates Occur

Duplicate certificates commonly appear due to:

  1. Certificate Renewal Confusion — New certificate installed, old one not removed
  2. Misconfiguration — Certificate imported multiple times into different stores
  3. Automation Errors — Renewal scripts create new certs without removing old ones
  4. Cross-Store Issues — Same certificate exists in both LocalMachine and CurrentUser stores
  5. Manual Intervention — Administrator copies certificates between systems without cleanup

Why This Matters

Duplicate certificates create multiple problems:

Problem Impact Risk Level
Private Key Risk Multiple duplicates with private keys: applications may select wrong certificate ⚠️ HIGH
Renewal Confusion Old expired cert exists alongside new one: tracking becomes difficult ⚠️ MEDIUM
Storage Waste Unnecessary duplicate storage consumes space and complicates inventory ✅ LOW
Compliance Issues Certificate inventory audits find unexpected duplicates ⚠️ MEDIUM
Application Errors App selects expired duplicate instead of valid certificate ⚠️ HIGH

Duplicate Detection Scenarios

Scenario 1: Same Store Duplicates

Setup: Create identical certificates in the same certificate store.

# Create first certificate
$cert1 = New-SelfSignedCertificate `
    -Subject "CN=duplicate.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Duplicate Test - Copy 1"

# Create second certificate (same subject)
$cert2 = New-SelfSignedCertificate `
    -Subject "CN=duplicate.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Duplicate Test - Copy 2"

# Both certificates now in Cert:\LocalMachine\My with same Subject but different thumbprints
Write-Host "Cert1 Thumbprint: $($cert1.Thumbprint)"
Write-Host "Cert2 Thumbprint: $($cert2.Thumbprint)"

Expected Result: Nodinite shows WARNING

  • Alert message: Duplicate Certificate Detected - Subject: CN=duplicate.test.com
  • Shows count: 2 certificates with identical Subject/SAN
  • Details page displays both thumbprints
  • Lists thumbprints: $($cert1.Thumbprint | Select-Object -First 8)... and $($cert2.Thumbprint | Select-Object -First 8)...

Scenario 2: High-Risk Duplicates (Multiple Private Keys)

Setup: Create duplicate certificates where both have private keys.

# Create first certificate WITH private key
$cert1 = New-SelfSignedCertificate `
    -Subject "CN=privatekey.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Private Key Duplicate - Original"

# Verify private key exists
$has_key_1 = $cert1.HasPrivateKey
Write-Host "Cert1 Has Private Key: $has_key_1"

# Create second certificate WITH private key (same subject)
$cert2 = New-SelfSignedCertificate `
    -Subject "CN=privatekey.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Private Key Duplicate - Renewal"

# Verify second has private key
$has_key_2 = $cert2.HasPrivateKey
Write-Host "Cert2 Has Private Key: $has_key_2"

Expected Result: Nodinite shows ERROR with high-risk indicator

  • Alert message: High-Risk Duplicate Certificate - Multiple private keys detected
  • "High Risk" badge displayed prominently
  • Critical message: Applications may select wrong certificate with unpredictable results
  • Recommendation: Remove old certificate immediately
  • Both thumbprints listed for removal action

Scenario 3: Cross-Store Duplicates

Setup: Create same certificate in both LocalMachine and CurrentUser stores.

# Create certificate in LocalMachine store
$localMachineCert = New-SelfSignedCertificate `
    -Subject "CN=crossstore.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Cross-Store Duplicate - Machine"

# Export certificate
$certPath = "C:\temp\crossstore-cert.cer"
Export-Certificate -Cert $localMachineCert -FilePath $certPath -Force | Out-Null

# Import same certificate to CurrentUser store
Import-Certificate -FilePath $certPath -CertStoreLocation Cert:\CurrentUser\My | Out-Null

# Verify duplicates exist in both stores
Write-Host "LocalMachine: $($localMachineCert.Thumbprint)"
Write-Host "Thumbprint exists in both LocalMachine\My and CurrentUser\My"

# Cleanup temp file
Remove-Item $certPath -Force

Expected Result: Nodinite shows WARNING with cross-store indicator

  • Alert message: Cross-Store Duplicate Detected - Certificate exists in multiple stores
  • Shows stores: Cert:\LocalMachine\My and Cert:\CurrentUser\My
  • Displays both locations in details
  • Recommendation: Remove from unnecessary stores

Scenario 4: Renewal Success (Single Valid Certificate)

Setup: Proper certificate renewal cleanup.

# Create original certificate
$original = New-SelfSignedCertificate `
    -Subject "CN=renewal.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddDays(30) `
    -FriendlyName "Valid Renewal - Original"

# Create new certificate (renewal)
$renewed = New-SelfSignedCertificate `
    -Subject "CN=renewal.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -NotAfter (Get-Date).AddYears(1) `
    -FriendlyName "Valid Renewal - New"

# IMPORTANT: Remove old certificate after renewal
Remove-Item "Cert:\LocalMachine\My\$($original.Thumbprint)" -Force

# Verify only new certificate remains
$remaining = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq "CN=renewal.test.com" }
Write-Host "Remaining certificates with subject: $($remaining.Count)"

Expected Result: Nodinite shows OK status

  • No duplicate warnings after cleanup
  • Only one certificate with Subject CN=renewal.test.com
  • Applications reliably select correct certificate

Scenario 5: Allowed Duplicates (Within Threshold)

Setup: Multiple versions within acceptable threshold.

# Configure Nodinite: MaxAllowedDuplicates = 2
# This means 1 alert trigger (duplicates exceed threshold of 1)

# Create two certificates (acceptable if threshold is 2)
$cert1 = New-SelfSignedCertificate `
    -Subject "CN=threshold.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -FriendlyName "Threshold Cert 1"

$cert2 = New-SelfSignedCertificate `
    -Subject "CN=threshold.test.com" `
    -CertStoreLocation Cert:\LocalMachine\My `
    -FriendlyName "Threshold Cert 2"

# If MaxAllowedDuplicates = 2: No warning (count equals threshold)
# If MaxAllowedDuplicates = 1: Warning (count exceeds threshold)

Expected Result: Depends on configuration

  • If MaxAllowedDuplicates = 2 and count is 2: OK status (at threshold)
  • If MaxAllowedDuplicates = 1 and count is 2: WARNING status (exceeds threshold)

Configuration Options

Detection Settings

Nodinite provides four configuration options for duplicate detection:

Setting Description Default Impact
Detect Duplicates Master toggle for duplicate detection feature false (disabled) When enabled, all other settings active
Alert on Private Key Duplicates High-severity alerts when multiple duplicates have private keys true Shows ERROR severity, marks as High-Risk
Alert on Cross-Store Duplicates Detect duplicates across different certificate stores (LocalMachine vs CurrentUser) true Identifies cross-store inventory issues
Max Allowed Duplicates Threshold: alert triggers when duplicate count exceeds this number 1 Setting to 1 means any duplicate triggers alert; 2 allows one renewal in progress

How to Configure

  1. Navigate to AdministrationSettingsCertificate Monitoring
  2. Find the Duplicates tab
  3. Enable Detect Duplicate Certificates toggle
  4. Adjust individual alert settings based on your organization's policy:
    • Private Key Duplicates: Enable for strict enforcement (recommended)
    • Cross-Store Duplicates: Enable if standardizing on single store location
    • Max Allowed Duplicates: Set to 1 for strict, 2 if renewing in progress
  5. Click Save and restart monitoring service

Troubleshooting

Duplicate Alert But Renewal In Progress

Situation: Legitimate renewal creates temporary duplicate.

Solution:

  1. After renewal complete and verified in production
  2. Navigate to old certificate details
  3. Click Remove Certificate to delete old version
  4. Alert clears after next monitoring cycle

Best Practice: Schedule certificate removal 24-48 hours after successful renewal to verify new cert is working.

High-Risk Warning: Multiple Private Keys

Situation: Both old and new certificates have private keys.

Action Required:

  1. Identify old certificate (check expiration date or "Renewed" metadata)

  2. Remove old certificate immediately:

    Remove-Item "Cert:\LocalMachine\My\<OLD_THUMBPRINT>" -Force
    
  3. Verify only new certificate remains:

    $remaining = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq "CN=yourdomain.com" }
    $remaining | Select-Object FriendlyName, Thumbprint, NotAfter
    
  4. Restart applications/services to ensure they use new certificate

  5. Alert clears after removal and monitoring cycle completes

Cross-Store Duplicates Detected

Situation: Same certificate exists in multiple stores.

Decision: Determine which store is authoritative:

  • LocalMachine — For services, preferred for production
  • CurrentUser — For user-specific applications or testing

Solution (example: keeping LocalMachine only):

# Export from LocalMachine (authoritative)
$cert = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Thumbprint -eq "ABC123..." }
Export-Certificate -Cert $cert -FilePath "C:\backup\cert-backup.cer" -Force

# Remove from CurrentUser
Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Thumbprint -eq "ABC123..." } | Remove-Item

False Positive: Different Certificates With Same Name

Situation: Warning for two certificates that look identical but are different.

Check: Verify thumbprints are actually different:

# List all certificates with specific subject
Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq "CN=test.com" } | Select-Object FriendlyName, Thumbprint, NotAfter

If Thumbprints Different: These are legitimate duplicates—use troubleshooting steps above.

If Thumbprints Same: Report as false positive—duplicate detection matched incorrectly.

Best Practices

  1. Automate Renewal Cleanup — Configure renewal scripts to remove old certificate after verification
  2. Verify Before Deleting — Always confirm new certificate working before removing old one
  3. Set Appropriate Threshold — Use MaxAllowedDuplicates = 1 for strict enforcement, 2 if temporary duplicates acceptable during renewal
  4. Enable Private Key Alerts — Critical setting to catch high-risk scenarios before applications fail
  5. Monitor Cross-Store — Enable if standardizing certificate locations; disable if cross-store duplication is intentional
  6. Document Renewal Process — Create runbook: deploy new cert → verify 24-48 hours → remove old cert → document in change log
  7. Quarterly Audits — Review certificate inventory quarterly to identify any long-standing duplicates
  8. Test Removal Steps — Practice certificate removal in test environment before production renewal

Batch Duplicate Certificate Testing Script

Create multiple test scenarios to validate duplicate detection:

# Nodinite Duplicate Certificate Detection Testing Suite
# Tests duplicate detection across same store, cross-store, and private key scenarios

Write-Host "=== Nodinite Duplicate Certificate Detection Testing Suite ===" -ForegroundColor Magenta
Write-Host "Creating comprehensive duplicate certificate test scenarios..." -ForegroundColor Cyan

# PowerShell 7 compatibility check
if ($PSVersionTable.PSVersion.Major -ge 7) {
    Write-Host "Note: Running in PowerShell $($PSVersionTable.PSVersion.Major). Some certificate operations work best in Windows PowerShell 5.1" -ForegroundColor Yellow
}

$testCertificates = @()
$testErrors = @()

try {
    Write-Host "`n Creating duplicate certificate test scenarios" -ForegroundColor Blue
    
    # Scenario 1: Same Store Duplicates
    Write-Host "`n[Scenario 1/5] Creating duplicates in LocalMachine\My store..." -ForegroundColor Green
    try {
        $dup1 = New-SelfSignedCertificate `
            -Subject "CN=duplicate.test.com" `
            -DnsName "duplicate.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Duplicate Test - Original" `
            -ErrorAction Stop
        
        $dup2 = New-SelfSignedCertificate `
            -Subject "CN=duplicate.test.com" `
            -DnsName "duplicate.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Duplicate Test - Renewal" `
            -ErrorAction Stop
        
        $testCertificates += @{ Scenario = "Same Store"; Subject = "CN=duplicate.test.com"; Count = 2; Store = "LocalMachine\My"; Thumbprints = @($dup1.Thumbprint, $dup2.Thumbprint) }
        Write-Host " Created 2 duplicate certificates in LocalMachine\My" -ForegroundColor Green
        Write-Host "  • Thumbprint 1: $($dup1.Thumbprint.Substring(0,16))..." -ForegroundColor White
        Write-Host "  • Thumbprint 2: $($dup2.Thumbprint.Substring(0,16))..." -ForegroundColor White
    }
    catch {
        $testErrors += "Scenario 1 (Same Store Duplicates): $_"
        Write-Host " Failed to create same-store duplicates: $_" -ForegroundColor Red
    }
    
    # Scenario 2: High-Risk Private Key Duplicates
    Write-Host "`n[Scenario 2/5] Creating high-risk duplicates with private keys..." -ForegroundColor Green
    try {
        $privkey1 = New-SelfSignedCertificate `
            -Subject "CN=privatekey.test.com" `
            -DnsName "privatekey.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Private Key Risk - Original" `
            -ErrorAction Stop
        
        $privkey2 = New-SelfSignedCertificate `
            -Subject "CN=privatekey.test.com" `
            -DnsName "privatekey.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Private Key Risk - Duplicate" `
            -ErrorAction Stop
        
        # Verify both have private keys
        $key1_has = $privkey1.HasPrivateKey
        $key2_has = $privkey2.HasPrivateKey
        
        $testCertificates += @{ Scenario = "High-Risk Private Keys"; Subject = "CN=privatekey.test.com"; Count = 2; PrivateKeys = @($key1_has, $key2_has); RiskLevel = "HIGH" }
        Write-Host " Created 2 high-risk duplicate certificates with private keys" -ForegroundColor Green
        Write-Host "  • Certificate 1 has private key: $key1_has" -ForegroundColor White
        Write-Host "  • Certificate 2 has private key: $key2_has" -ForegroundColor White
        Write-Host "  • Expected Alert: ERROR - High-Risk Duplicate (multiple private keys)" -ForegroundColor Yellow
    }
    catch {
        $testErrors += "Scenario 2 (Private Key Duplicates): $_"
        Write-Host " Failed to create private key duplicates: $_" -ForegroundColor Red
    }
    
    # Scenario 3: Cross-Store Duplicates
    Write-Host "`n[Scenario 3/5] Creating cross-store duplicates..." -ForegroundColor Green
    try {
        # Create in LocalMachine
        $crossstore1 = New-SelfSignedCertificate `
            -Subject "CN=crossstore.test.com" `
            -DnsName "crossstore.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Cross-Store - Machine Store" `
            -ErrorAction Stop
        
        # Export for import to CurrentUser
        $exportPath = "C:\temp\crossstore-cert-$([Guid]::NewGuid().ToString().Substring(0,8)).cer"
        Export-Certificate -Cert $crossstore1 -FilePath $exportPath -Force -ErrorAction Stop | Out-Null
        
        # Import to CurrentUser
        Import-Certificate -FilePath $exportPath -CertStoreLocation Cert:\CurrentUser\My -ErrorAction Stop | Out-Null
        
        $testCertificates += @{ Scenario = "Cross-Store"; Subject = "CN=crossstore.test.com"; Stores = @("Cert:\LocalMachine\My", "Cert:\CurrentUser\My"); ExportPath = $exportPath }
        Write-Host " Created cross-store duplicate certificate" -ForegroundColor Green
        Write-Host "  • LocalMachine\My: $($crossstore1.Thumbprint.Substring(0,16))..." -ForegroundColor White
        Write-Host "  • CurrentUser\My: [Same thumbprint, different store]" -ForegroundColor White
    }
    catch {
        $testErrors += "Scenario 3 (Cross-Store Duplicates): $_"
        Write-Host " Failed to create cross-store duplicates: $_" -ForegroundColor Red
    }
    
    # Scenario 4: Threshold Test (3 duplicates)
    Write-Host "`n[Scenario 4/5] Creating multiple duplicates to test threshold..." -ForegroundColor Green
    try {
        $threshold1 = New-SelfSignedCertificate `
            -Subject "CN=threshold.test.com" `
            -DnsName "threshold.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Threshold Test - Cert 1" `
            -ErrorAction Stop
        
        $threshold2 = New-SelfSignedCertificate `
            -Subject "CN=threshold.test.com" `
            -DnsName "threshold.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Threshold Test - Cert 2" `
            -ErrorAction Stop
        
        $threshold3 = New-SelfSignedCertificate `
            -Subject "CN=threshold.test.com" `
            -DnsName "threshold.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Threshold Test - Cert 3" `
            -ErrorAction Stop
        
        $testCertificates += @{ Scenario = "Threshold Test"; Subject = "CN=threshold.test.com"; Count = 3; ExpectedAlert = "If MaxAllowedDuplicates < 3" }
        Write-Host " Created 3 duplicate certificates to test threshold" -ForegroundColor Green
        Write-Host "  • Alert if MaxAllowedDuplicates = 1 or 2" -ForegroundColor White
        Write-Host "  • No alert if MaxAllowedDuplicates >= 3" -ForegroundColor White
    }
    catch {
        $testErrors += "Scenario 4 (Threshold Test): $_"
        Write-Host " Failed to create threshold test certificates: $_" -ForegroundColor Red
    }
    
    # Scenario 5: Renewal Success (No Duplicates)
    Write-Host "`n[Scenario 5/5] Creating proper renewal (no duplicates)..." -ForegroundColor Green
    try {
        $original = New-SelfSignedCertificate `
            -Subject "CN=renewal.test.com" `
            -DnsName "renewal.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddDays(30) `
            -FriendlyName "Renewal Test - Original (Expiring)" `
            -ErrorAction Stop
        
        $renewed = New-SelfSignedCertificate `
            -Subject "CN=renewal.test.com" `
            -DnsName "renewal.test.com" `
            -CertStoreLocation Cert:\LocalMachine\My `
            -NotAfter (Get-Date).AddYears(1) `
            -FriendlyName "Renewal Test - New" `
            -ErrorAction Stop
        
        # Remove old certificate (proper cleanup)
        Remove-Item "Cert:\LocalMachine\My\$($original.Thumbprint)" -Force -ErrorAction Stop
        
        $testCertificates += @{ Scenario = "Proper Renewal"; Subject = "CN=renewal.test.com"; Status = "Old removed"; Remaining = $renewed.Thumbprint }
        Write-Host " Created and cleaned up renewal (old cert removed)" -ForegroundColor Green
        Write-Host "  • Old Certificate: $($original.Thumbprint.Substring(0,16))... [REMOVED]" -ForegroundColor White
        Write-Host "  • New Certificate: $($renewed.Thumbprint.Substring(0,16))... [KEPT]" -ForegroundColor White
        Write-Host "  • Expected Alert: NONE (proper cleanup)" -ForegroundColor Green
    }
    catch {
        $testErrors += "Scenario 5 (Proper Renewal): $_"
        Write-Host " Failed to create proper renewal test: $_" -ForegroundColor Red
    }
}
catch {
    Write-Host " Unexpected error during test setup: $_" -ForegroundColor Red
}

# Summary Report
Write-Host "`n" -ForegroundColor White
Write-Host "=== Test Scenario Summary ===" -ForegroundColor Cyan
Write-Host " Test Scenarios Created: $($testCertificates.Count)/5" -ForegroundColor Blue

if ($testCertificates.Count -gt 0) {
    Write-Host "`nScenarios:" -ForegroundColor Green
    foreach ($scenario in $testCertificates) {
        Write-Host "  • $($scenario.Scenario) - Subject: $($scenario.Subject)" -ForegroundColor White
    }
}

if ($testErrors.Count -gt 0) {
    Write-Host "`n Errors Encountered:" -ForegroundColor Yellow
    foreach ($error in $testErrors) {
        Write-Host "  • $error" -ForegroundColor Yellow
    }
}

Write-Host "`n Configuration:" -ForegroundColor Blue
Write-Host "  • Enable in Settings: Administration → Certificate Monitoring → Duplicates tab" -ForegroundColor White
Write-Host "  • Set DetectDuplicateCertificates = true" -ForegroundColor White
Write-Host "  • Enable AlertOnDuplicatesWithPrivateKey for high-risk detection" -ForegroundColor White
Write-Host "  • Set MaxAllowedDuplicates = 1 (strict) or 2 (renewal in progress)" -ForegroundColor White
Write-Host "  • Restart monitoring service" -ForegroundColor White
Write-Host "  • Verify duplicate alerts appear in Certificate View" -ForegroundColor White

Write-Host "`n Test setup complete! Duplicate detection scenarios ready for validation." -ForegroundColor Green

Cleanup: Remove Duplicate Certificate Test Certificates

Remove all test certificates after validation:

# Cleanup Nodinite Duplicate Certificate Test Certificates

Write-Host "=== Cleanup: Duplicate Certificate Test Certificates ===" -ForegroundColor Magenta
Write-Host "Removing all test duplicate certificates..." -ForegroundColor Cyan

$testSubjects = @(
    "CN=duplicate.test.com",
    "CN=privatekey.test.com",
    "CN=crossstore.test.com",
    "CN=threshold.test.com",
    "CN=renewal.test.com"
)

$removedCount = 0
$cleanupErrors = @()

# Remove from LocalMachine store
Write-Host "`n Removing certificates from LocalMachine\My..." -ForegroundColor Blue
foreach ($subject in $testSubjects) {
    try {
        $certs = Get-ChildItem Cert:\LocalMachine\My | Where-Object { $_.Subject -eq $subject }
        foreach ($cert in $certs) {
            Remove-Item "Cert:\LocalMachine\My\$($cert.Thumbprint)" -Force -ErrorAction Stop
            Write-Host " Removed $($cert.FriendlyName) (Thumbprint: $($cert.Thumbprint.Substring(0,8))...)" -ForegroundColor Green
            $removedCount++
        }
    }
    catch {
        $cleanupErrors += "Failed to remove subject '$subject' from LocalMachine: $_"
        Write-Host " Failed to remove subject '$subject': $_" -ForegroundColor Red
    }
}

# Remove from CurrentUser store
Write-Host "`n Removing certificates from CurrentUser\My..." -ForegroundColor Blue
foreach ($subject in $testSubjects) {
    try {
        $certs = Get-ChildItem Cert:\CurrentUser\My | Where-Object { $_.Subject -eq $subject }
        foreach ($cert in $certs) {
            Remove-Item "Cert:\CurrentUser\My\$($cert.Thumbprint)" -Force -ErrorAction Stop
            Write-Host " Removed $($cert.FriendlyName) from CurrentUser\My" -ForegroundColor Green
            $removedCount++
        }
    }
    catch {
        $cleanupErrors += "Failed to remove subject '$subject' from CurrentUser: $_"
        Write-Host " Failed to remove from CurrentUser: $_" -ForegroundColor Yellow
    }
}

# Cleanup temporary export files
Write-Host "`n Removing temporary export files..." -ForegroundColor Blue
try {
    $tempFiles = Get-ChildItem "C:\temp\crossstore-cert-*.cer" -ErrorAction SilentlyContinue
    foreach ($file in $tempFiles) {
        Remove-Item $file.FullName -Force -ErrorAction Stop
        Write-Host " Removed temporary file: $($file.Name)" -ForegroundColor Green
    }
}
catch {
    Write-Host " Note: Some temporary files may not exist" -ForegroundColor Yellow
}

# Cleanup Summary
Write-Host "`n=== Cleanup Summary ===" -ForegroundColor Cyan
Write-Host " Test Certificates Removed: $removedCount" -ForegroundColor Green

if ($cleanupErrors.Count -gt 0) {
    Write-Host "`n Errors During Cleanup:" -ForegroundColor Yellow
    foreach ($error in $cleanupErrors) {
        Write-Host "  • $error" -ForegroundColor Yellow
    }
    Write-Host "`nNote: Some certificates may have already been removed. Review above for any critical errors." -ForegroundColor Yellow
}

Write-Host "`n Cleanup complete! Test certificates removed." -ForegroundColor Green

Next Step