尝试将多个变量解析为 openssl 命令的 powershell foreach 循环

Attempting to parse multiple variables into a powershell foreach loop for openssl command

我正在尝试利用 Powershell 自动创建一些使用 Openssl 的 PFX 证书。 我正在尝试创建一个 foreach 循环,该循环使用 openssl pkcs12 命令获取私有 pem 密钥和颁发的证书并推出 pfx 文件。 我试图创建一个对象,foreach 循环可以在该对象上获取数据,但我不相信正确的值正在被解析到 openssl 命令。

$openssldir = "C:\openssl-1.1\x64\bin"
$certlocation = "C:\openssl-1.1\x64\bin\Certs"
$keylocation = "C:\openssl-1.1\x64\bin\Keys"
$pfxlocation = "C:\openssl-1.1\x64\bin\PFX"

$certs = (Get-ChildItem -path $certlocation -File).Name
$keys = (Get-ChildItem -path $keylocation -File).Name


$certpath = $certs | foreach{".\Certs\" + $_}
$keypath = $keys | foreach{".\Keys\" + $_}

set-location -Path $openssldir


$a = @()
$obj = New-Object PSObject
$obj | Add-Member -type NoteProperty -Name 'cert' -Value $certpath
$obj | Add-Member -Type NoteProperty -Name 'key' -Value $keypath


$a += $obj



ForEach($item in $a){
$pfx = $item.cert
$pfxfile = $pfx.replace(".cer",".pfx")
.\openssl.exe pkcs12 -export -out PFX/$pfxfile -inkey $item.key -in $item.cert -password pass: 
}

我可以手动 运行 命令,它没有问题,我什至可以 运行 使用数组中的特定条目的命令,如:

.\openssl.exe pkcs12 -export -out PFX/test.pfx -inkey $item.key[0] -in $item.cert[0] -password pass: 

我可能只是遇到了一些语法错误或愚蠢的问题,所以非常感谢您的帮助!

瑞安

当您构建 $obj 对象时,您只创建了一个对象,其中 属性 包含一个 $certpath 路径数组,另一个 属性 包含一个 $keypath 路径。我相信您的意图是创建包含一个匹配的证书路径和密钥路径的单独对象。如果是这样,您需要一些额外的逻辑来执行此匹配,并使用一些循环将适当的单个证书路径和密钥路径放在每个 $obj 中。

很遗憾,我无法测试此代码,但我认为它应该可以工作。 $a 变量上的 foreach 循环是与您的代码的主要区别,也是证书与密钥匹配的地方。我还将 pfx 文件名的代码移到了这里。

$openssldir = 'C:\openssl-1.1\x64\bin'
$certlocation = 'C:\openssl-1.1\x64\bin\Certs'
$keylocation = 'C:\openssl-1.1\x64\bin\Keys'
$pfxlocation = 'C:\openssl-1.1\x64\bin\PFX'

$opensslExe = "$openssldir\openssl.exe"

$certs = Get-ChildItem -Path $certlocation -File
$keys = Get-ChildItem -Path $keylocation -File

$a = foreach ($cert in $certs) {
    [PSCustomObject]@{
        cert    = $cert.FullName
        key     = ($keys | 
                Where-Object( { $_.BaseName -like $cert.BaseName }) | 
                Select-Object -First 1).FullName
        pfxfile = $cert.Name.Replace('.cer', '.pfx')
    }    
}

ForEach ($item in $a) {
    & $opensslExe pkcs12 -export -out "$pfxlocation/$($item.pfxfile)" -inkey $item.key -in $item.cert -password pass: 
}