如何比较powershell中的不同对象

时间:2017-12-21 10:21:44

标签: powershell

我已经使用以下命令从更新列表中获取KB值,因为我必须检查KB值的完全匹配我已经使用-eq -match的所有可能性,但是-eq是完美的,但它不起作用在我的情况下,请提出建议。

$patchID="KB3039714"
$Session = New-Object -ComObject "Microsoft.Update.Session"

$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$a = $Searcher.QueryHistory(0, $historyCount) | Select-Object 
@{Name="KB";Expression={[regex]::match($_.Title,'\
(([^\)]+)\)').Groups[1].Value}}
foreach($c in $a){
if($c -eq $patchID){
$Status="True"
write-host "exe File Type"
}else{
write-host "Given patchID is not available"
}}

1 个答案:

答案 0 :(得分:0)

当你写出$ c时,它会显示:

enter image description here

因此,如果要将输出与字符串$patchID进行比较,则必须将Object的Attribute“KB”与字符串进行比较。 要么是这样的:

$patchID="KB3039714"
$Session = New-Object -ComObject "Microsoft.Update.Session"

$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$a = $Searcher.QueryHistory(0, $historyCount) | Select-Object @{Name="KB";Expression={[regex]::match($_.Title,'\(([^\)]+)\)').Groups[1].Value}}
foreach($c in $a){
if($c.KB -eq $patchID){
$Status="True"
write-host "exe File Type"
}else{
write-host "Given patchID is not available"
}}

或者像这样:

$patchID="KB3039714"
$Session = New-Object -ComObject "Microsoft.Update.Session"
$Searcher = $Session.CreateUpdateSearcher()
$historyCount = $Searcher.GetTotalHistoryCount()
$a = $Searcher.QueryHistory(0, $historyCount) | Select-Object 
@{Name="KB";Expression={[regex]::match($_.Title,'\(([^\)]+)\)').Groups[1].Value}}
if($a.KB.Contains($patchID)){
$Status="True"
write-host "exe File Type"
}else{
write-host "Given patchID is not available"
}}

也许你应该多读一下Powershell-Objects,本文解释得非常好:https://technet.microsoft.com/en-us/library/ff730946.aspx

相关问题