Using 'if' for a string variable in powershell

SAMUEL VALAPARLA 131 Reputation points
2022-09-28T11:10:54.81+00:00

Hi All,

I'm just trying to understand the usage of the 'if' in a specific context.

From my understanding when you run an If statement, PowerShell evaluates the <test1> conditional expression as true or false.

However, in the below piece of code, we're seeing the 'if' operator is used on a variable that contains a lot of data content (which has been a result of a command retrieving certain info)

$LatestLog = Get-EventLog -LogName System -After (Get-Date).AddDays(-5)

if($LatestGPLog) #if machine processed GPO within 7 days
{
return $true
}

In the absence of a conditional expression in the above statement, is the 'if' statement just checking for presence or absence of content within the variable and proceeding further? Or am I missing something?

Thanks in advance.

  • SV
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2022-09-28T11:30:30.763+00:00

    Hi @SAMUEL VALAPARLA ,

    the if($LatestGPLog) is true if the variable $LatestGPLog contains "something", which means $LatestGPLog is "not Null" or "is not empty".
    Instead of if($LatestGPLog) you can use if($LatestGPLog -ne $null)

    The opposite of if($LatestGPLog) - "variable is not Null" is if(!$LatestGPLog) - variable is "!empty or null"
    Or if($LatestGPLog -eq $null)

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


2 additional answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2022-09-28T14:55:57.253+00:00

    Regardless of the two earlier answers, they aren't completely true.

    Given the "if the variable contains something" statement, what do you think the result of this little bit of code will be? The variable $x contains an integer, and that qualifies as "something", no?

    $x = 0  
    if ($x){$true} else {$false}  
    $null -eq $x  
    
    1 person found this answer helpful.

  2. Olaf Helper 47,436 Reputation points
    2022-09-28T11:32:35.963+00:00

    just checking for presence or absence of content within the variable

    Right, as a vers simple example:

    $var  
    if ($var) { Write-Host "Has value" } else { Write-Host "Has no value" }  
    $var = 1234  
    if ($var) { Write-Host "Has value" } else { Write-Host "Has no value" }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.