Matt White
Matt White

Reputation: 15

If/else statement to see if windows updates were installed during a specific window

Can someone help me? I would like to run a powershell script on a computer that tells me yes or no if updates were installed during a specific time frame and the way I wrote this, it keeps returning not installed. Any ideas please?

$hotfix1 = Get-HotFix | 

Where 
    ($_.InstalledOn -gt "10/13/2020" -AND $_.InstalledOn -lt "10/16/2020") 


If ($hotfix1 -eq "True") {
write-host "Hotfix is installed"
}
else {
write-host "Hotfix is NOT installed"
}

Upvotes: 0

Views: 964

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25041

You can use the following code:

$hotfix1 = Get-HotFix | Where { $_.InstalledOn -gt "10/13/2020" -AND $_.InstalledOn -lt "10/16/2020" }
if ($hotfix1) {
    Write-Host "Hotfix is installed"
} else { 
    Write-Host "Hotfix is NOT installed"
}

Since you are filtering based on the current object in the pipeline ($_), you must use a script block ({}).

Where is an alias for Where-Object. When you pass a script block as a positional parameter, the script block is bound to the -FilterScript parameter of the command.

If a variable is a null, empty string/set, boolean false, or 0 value, then PowerShell returns False when the variable is converted to a Boolean type. If the variable contains a nonzero number, a boolean true, or a non-empty object, PowerShell returns True when converted to Boolean. Therefore, you only need to have the variable evaluated in the if statement conditional as PowerShell will convert it to Boolean as the expression is evaluated.


To evaluate the if statements the way you were intending, you would need to convert $hotfix1 to Boolean before doing the comparison. Since PowerShell likes to be helpful by coercing the right-hand side (RHS) to match types with the LHS, you can get away with leaving the RHS as 'true'; however, even though that is syntactically correct, it is not logically correct. 'true' and 'false' are strings and not booleans because quotes are used. So when strings are converted to boolean, the character arrangement of the strings does not matter as PowerShell only cares if they are empty or not.

# A longer hand way of using correct syntax and logic
if ([boolean]$hotfix1 -eq $true) { Write-Host "Hotfix installed" }

# The below syntax is not recommended because both statements evaluate  equally!
# Works only because 'true' is coerced into [boolean]'true', which evaluates to true.
# [boolean]'false' also evaluates to true because the string false is not an empty string
if ([boolean]$hotfix1 -eq 'True') { Write-Host "Hotfix installed" }
if ([boolean]$hotfix1 -eq 'False') { Write-Host "Hotfix installed" }

Upvotes: 1

Related Questions