Search code examples
powershellcertificatekeytool

How to check certificate already installed in keystore by `Powershell`?


I want to automatically install the certificate when its not installed. I can check it manually:

keytool -list -keystore $Cacerts_trustStore -alias myCertAlias

But I want to use this function:

#Check keystore file is not existing or keystore does not contains certificate with alias in it
if (-not (Test-Path $Cacerts_trustStore) -or -not (<CheckCertIsExistsByAlias>)) {
    #Call form to find certificate to install
    Add-Type -AssemblyName System.Windows.Forms
    $dialog = New-Object System.Windows.Forms.OpenFileDialog
    $dialog.Multiselect = $false
    $dialog.ShowDilog()
    $certPath = $dialog.FileName
    #Installing the certificate
    & keytool -import -alias myCertAlias -keystore $Cacerts_trustStore -file $certPath 
}

I tried:

if (-not (Test-Path $Cacerts_trustStore) -or -not (keytool -list -keystore $Cacerts_trustStore -alias myCertAlias)) {

But, obviously, it's not working because command output is not Boolean.

Any ideas? Thanks!


Solution

  • # Function to check if a certificate with a given alias exists in the keystore
    function Check-CertExists {
        param (
            [string]$keystorePath,
            [string]$alias
        )
    
        $output = & keytool -list -keystore $keystorePath -alias $alias 2>&1
        return $output -match "Alias name: $alias"
    }
    
    # Your main script
    $Cacerts_trustStore = "path/to/your/keystore"
    $certAlias = "myCertAlias"
    
    # Check if keystore file is not existing or keystore does not contain certificate with alias in it
    if (-not (Test-Path $Cacerts_trustStore) -or -not (Check-CertExists -keystorePath $Cacerts_trustStore -alias $certAlias)) {
        # Call form to find certificate to install
        Add-Type -AssemblyName System.Windows.Forms
        $dialog = New-Object System.Windows.Forms.OpenFileDialog
        $dialog.Multiselect = $false
        $dialog.ShowDialog()
        $certPath = $dialog.FileName
        
        # Installing the certificate
        & keytool -import -alias $certAlias -keystore $Cacerts_trustStore -file $certPath
    }