首页 > 解决方案 > 应用 Windows 更新前的数据库检查

问题描述

这就是我想要做的。

  1. 查询数据库以检查正在运行的作业
  2. 如果没有作业正在运行,则运行 Windows 更新
  3. 如果有作业正在运行,它会填充变量
  4. 如果没有作业正在运行,则变量保持为空。

我遇到的问题是,如果查询发生错误,则变量保持为空,然后运行 ​​Windows 更新。

我正在寻找如何正确运行此检查并且仅在变量为空时才运行 Windows 更新的想法。

  $result = Invoke-Sqlcmd -ServerInstance  'ipaddress,port' -Database 'instance' -Query $testQuery -QueryTimeout 15


if (!$result)
{
    Get-WUInstall -WindowsUpdate Software -AcceptAll
}

标签: powershell

解决方案


如果分配$result会给你一个错误,那么我会$error像这样跟踪变量:

$error.clear()
$result = Invoke-Sqlcmd -ServerInstance  'ipaddress,port' -Database 'instance' -Query $testQuery -QueryTimeout 15


if (!$result -and !$error)
{
    Get-WUInstall -WindowsUpdate Software -AcceptAll
}

测试用例:没有错误也没有结果

$error.clear()
$result = $null
if (!$result -and !$error) {
Write-Host "Updating Windows..."
}

Updating Windows...

测试用例:结果错误

$error.clear()
$result = Invoke-Sqlcmd -ServerInstance  'ipaddress,port' -Database 'instance' -Query $testQuery -QueryTimeout 15
Invoke-Sqlcmd : The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

if (!$result -and !$error) {
Write-Host "Updating Windows...."
}

[bool]$error
True
[bool]$result
False

$error.clear()只是清空$error变量。如果您希望该变量在整个脚本中跟踪您的错误,这可能并不完全明智。我只能假设,因为我只看到了你正在做的事情的一小部分。


推荐阅读