【问题标题】:Export-PfxCertificate with foreach scenario使用 foreach 方案导出 PfxCertificate
【发布时间】:2020-01-03 22:31:48
【问题描述】:

我在尝试将 Windows 商店中的证书导出为 .pfx 格式时遇到了一些问题

以下命令可以正常工作,

Get-ChildItem -Path Cert:\CurrentUser\My\**** | Export-PfxCertificate -FilePath "D:\a.pfx" -Password $securestring 

而这不是

Get-ChildItem -Path Cert:\CurrentUser\My | ? {$_.friendlyname -like "zxy*" }  | sort -Property FriendlyName | % { Export-PfxCertificate -FilePath "D:\$($_.friendlyname).pfx" -Password $securestring }

错误:Export-PfxCertificate:无法使用指定的命名参数解析参数集。

即使这样也没有

Get-ChildItem -Path Cert:\CurrentUser\My\*********** | Export-PfxCertificate -FilePath "D:\a.pfx" -Password (ConvertTo-SecureString -String $_.FriendlyName -Force -AsPlainText)

错误: ConvertTo-SecureString : 无法将参数绑定到参数“字符串”,因为它为空。

请多指教。。 提前致谢

【问题讨论】:

  • 当使用星号作为通配符时,一个就足够了。 ,第二个示例需要输入,第三个示例必须在 -Password {} 周围有一个脚本块,而不是括号 ()。
  • 感谢@LotPings,如果用于屏蔽指纹,使用 {} 也不起作用。本德尔的回答奏效了。

标签: powershell certificate ssl-certificate x509certificate


【解决方案1】:

您没有在第二个命令中将证书传递给Export-PfxCertificate,而是将找到的证书传递给ForEach-Object 子句,但没有使用块内的$PSItem。你有两个选择:

Get-ChildItem -Path Cert:\CurrentUser\My | ? {$_.friendlyname -like "zxy*" }  | sort -Property FriendlyName | % { $_ | Export-PfxCertificate -FilePath "D:\$($_.friendlyname).pfx" -Password $securestring }

或

Get-ChildItem -Path Cert:\CurrentUser\My | ? {$_.friendlyname -like "zxy*" }  | sort -Property FriendlyName | % { Export-PfxCertificate -Certificate $_ -FilePath "D:\$($_.friendlyname).pfx" -Password $securestring }

第一个将该迭代的证书对象通过管道传递给Export-PfxCertificate,而第二个提供证书作为直接参数。

为什么你的第三次尝试没有成功

我看到的第一件事是您将Get-ChildItem 传递给Export-PfxCertificate,它只需要一个证书作为参数。如果gci 返回多个证书,它就会爆炸。

其次,您尝试使用证书友好名称作为证书密码。不确定这是否是您的意图,但代码出错了,因为您尝试在上下文之外使用 $PSItem,并且返回的值最终是 $null 作为必需参数 - 您需要在 @ 987654332@ 或 Where-Object 脚本块使用 $PSItem 或其别名 $_。如果你这样做,它会起作用:

Get-ChildItem -Path Cert:\CurrentUser\My\*********** | ForEach-Object { $_ | Export-PfxCertificate -FilePath "D:\a.pfx" -Password ( ConvertTo-SecureString -String $_.FriendlyName -Force -AsPlainText ) }

请注意,我将命令的后半部分包装在 ForEach-Object 循环中 - 这解决了这两个问题,一次只输入一个证书,您还可以访问 FriendlyName 属性,因为那是当前可迭代的项目,在这种情况下应该是证书。

【讨论】:

  • 感谢 Bender,它成功了。但我不太明白它是如何工作的,你能在这里指出任何参考吗?
  • 另外,对于我的第三个命令,我将证书传递给导出命令,为什么不起作用?
猜你喜欢
  • 1970-01-01
  • 2016-09-04
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多