如何通过`Powershell`检查密钥库中已安装的证书?

问题描述 投票:0回答:1

我想在未安装证书时自动安装证书。 我可以手动检查:

keytool -list -keystore $Cacerts_trustStore -alias myCertAlias

但是我想使用这个功能:

#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 
}

我尝试过:

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

但是,显然,它不起作用,因为命令输出不是布尔值。

有什么想法吗? 谢谢!

powershell certificate keytool
1个回答
0
投票

# 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
}

© www.soinside.com 2019 - 2024. All rights reserved.