windows - 我如何在某些 'if' 语句中使用 Windows 版本标题来确定要检查哪些 Windows 更新?

标签 windows powershell scripting updates

我正在编写一个令人遗憾的脚本,旨在基本上从 Windows 7、8 和 8.1 中消除 Windows 10 的任何痕迹。几乎是 this 的脚本版本程序。脚本即将完成(我认为),但似乎我的某些 if 语句中的逻辑即使变量不正确也会执行。

这里是要记住的部分,为了清楚起见,在脚本的前面添加了创建 $Caption 变量的行:

$Caption = (Get-WmiObject win32_operatingsystem).caption

if ($Caption = 'Windows 8.1 Professional') {
  if (Get-Hotfix -id KB3044374) {
    Wusa /uninstall /kb:3044374 /quiet
    Start-Sleep -s 30
    Hide-WUUpdate -KBArticleID KB3044374 -Force
    Start-Sleep -s 20
  }
}

if ($Caption = 'Microsoft Windows 7 Professional') {
  if (Get-Hotfix -id KB2952664) {
    wusa /uninstall /kb:2952664 /quiet
    Start-Sleep -s 30
    Hide-WUUpdate -KBArticleID KB2952664 -Force
    Start-Sleep -s 20
  }
  if (Get-Hotfix -id KB2990214) {
    wusa /uninstall /kb:2990214 /quiet
    Start-Sleep -s 30
    Hide-WUUpdate -KBArticleID KB2990214 -Force
    Start-Sleep -s 20
  }
}

这不是一个完全破坏交易的因素,因为当未找到针对另一个 Windows 版本的更新时,代码仍会执行并给出简单的错误消息,但我想修复此错误以维护良好的编程原则。

最佳答案

Get-Hotfix cmdlet 不返回 bool 值。如果它存在于目标系统上,它会返回一个包含信息的对象。 If、Else 运算符期望 bool 值(逻辑 1 或 0)输入能够正常工作。

您要做的是像这样使用测量 (Measure-Object) cmdlet:

$m = get-hotfix -id KB3124200 | measure
if ($m.Count -gt 0) { //execute code if hotfix is present // }

这将为您提供准确的输出,以作为您的 If 语句的基础。

编辑:这一行:

If ($Caption = 'Microsoft Windows 7 Professional') {

应该是:

If ($Caption -eq 'Microsoft Windows 7 Professional')

This link包含有关 PowerShell 比较运算符的良好资源。

关于windows - 我如何在某些 'if' 语句中使用 Windows 版本标题来确定要检查哪些 Windows 更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34727514/

相关文章:

linux - Bash 脚本 : edit output of a variable

python - 多处理池示例不起作用并卡住内核

windows - 如何告诉 Windows 批处理脚本执行下一行而不等待上一行完成执行?

linux - 在 shell 脚本中使用\c

visual-studio - 在 powershell 中打开控制台应用程序

powershell - 微软在 PowerShell CmdLet 参数命名方面的一致性

windows - 检查是否安装了特定版本的程序

windows - 在 C# 应用程序中使用系统图标

windows - 如何在 Windows 机器上安装 autotools(autoconf、automake、aclocal、libtoolize pkgconfig)

powershell - MSMQ 发布消息