我正在尝试使用powershell检查所有服务器以查看是否已安装该修补程序或是否需要安装它。
如果我自己运行一些代码,它似乎工作但我的预期结果总是假定没有安装补丁。
#You can change this to find a specific patch
$patch = "KB2550978"
$installed ='no'
#Get all windows server from AD
Import-Module ActiveDirectory
$servers = Get-ADComputer -filter {(objectclass -eq "computer") -and (OperatingSystem -like "*Windows Server*")}
# Procces through Servers to find who is missing or has it installed
foreach ($server in $servers)
{
$hotfixes = Get-HotFix -ComputerName $server.name
foreach ($hotfix in $hotfixes)
{
If ($hotfix.hotfixid -like $patch)
{
$installed = 'yes'
}
}
if ($installed = 'no')
{
write-host $server.name "does not have $patch installed."
} Else {
Write-Host $server.name "has $patch installed!"
}
}
答案 0 :(得分:1)
我想我可以看到你的问题在哪里,你永远不会将$安装的值重置为'no'所以在找到你的第一个'是'后,所有连续的服务器也变为'是'。 alroc也是正确的,更有效地检查特定的修补程序而不是遍历all。这应该可以解决问题:
#You can change this to find a specific patch
$patch = "KB2550978"
#Get all windows server from AD
Import-Module ActiveDirectory
$servers = Get-ADComputer -filter {(objectclass -eq "computer") -and (OperatingSystem -like "*Windows Server*")}
# Procces through Servers to find who is missing or has it installed
foreach ($server in $servers)
{
$hotfix = Get-HotFix -ComputerName $server.name -Id $patch -ErrorAction 0;
if ($hotfix)
{
write-host $server.name "does not have $patch installed."
}
Else {
Write-Host $server.name "has $patch installed!"
}
}
答案 1 :(得分:-1)
答案中似乎存在逻辑错误。如果$ hotfix返回Get-Hotfix的结果,结果是肯定的(它找到了补丁),那么" if($ hotfix)"应该写安装的补丁程序,而Else则相反。我在验证了几台服务器之后在我的环境中运行了脚本,发现脚本返回相反的答案。简单更改为" If(!($ hotfix))"诀窍。