如何合并两个“列表"?在 PowerShell 中,当一个列表可能只是 Get-Item 中的一项时? [英] How do I merge two "lists" in PowerShell when one list might be just one item from Get-Item?

查看:40
本文介绍了如何合并两个“列表"?在 PowerShell 中,当一个列表可能只是 Get-Item 中的一项时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Get-ChildItem 来获取本地安装的证书.然后我想从我的本地证书存储中删除这些证书.如果我执行下面的脚本,它会在两个 Get-ChildItem 查询中返回多个项目时工作.但是如果在任一查询中只返回一个项目,则两个集合的添加将失败.仅仅因为只返回一个对象,实现只返回一个实例而不是一个实例的集合.这里的正确方法是什么?我不知道从我的查询返回的结果是否会产生 0、1 或多个证书.

I am using Get-ChildItem to fetch locally installed certs. Then I'd like to delete these certs from my local certificate store. If I execute the script below it will work when there is more than one item returned in both the Get-ChildItem queries. But if only one item is returned in either of the queries the addition of the two collections will fail. Simply because with only one object returned the implementation only returns one instance and not a collection of one. What is the right approach here? I won't know if the result(s) returned from my queries will result in 0, 1 or multiple certs.

$myCerts = Get-ChildItem cert:\CurrentUser\My | Where-Object { $_.Subject -like "CN=$certName" }
$trustedPeopleCerts = Get-ChildItem cert:\CurrentUser\TrustedPeople | Where-Object { $_.Subject -like "CN=$certName" }

$allCerts = $myCerts + $trustedPeopleCerts

foreach ($cert in $allCerts) {
    $store = Get-Item $cert.PSParentPath
    $store.Open('ReadWrite')
    $store.Remove($cert)
    $store.Close()
}

推荐答案

如果 $myCerts 可能只是单个项目,请使用数组子表达式运算符 @( ):

If $myCerts might just be a single item, use the array subexpression operator @( ):

$allCerts = @($myCerts) + $trustedPeopleCerts

这篇关于如何合并两个“列表"?在 PowerShell 中,当一个列表可能只是 Get-Item 中的一项时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆