Something wrong with If Else Loop

Hi Team,
I am going to post an if else issue that I can’t identify why this is happen.
Source File
Code that I write

$tar1=(Select-String -Pattern accounts -Path C:\type.txt).line if ($tar1::isemptyornull) {
'Err.. Required data not found'

} else {

$targ1=(Select-String -Pattern accounts, performing, "done test list operation" -Path C:\type.txt).line.trim()

}

“Following is the value”
$tar1

Please note, above quote is a part of main script, only this part is not working as expected.

The Story
From the attached link, you will get a file having some text. I want to pickup only specific text from that file, which is “accounts”. So I write the script like that. The file is located at C drive of my system. You can modify the codes as per your requirement.
Case 1: I want, if the string accounts available, then the line will be captured along with 2 more pattern(defined under else) and will be stored on $tar1 through $targ1.
Case 2: If the string will no be available then $tar1 will hold the pre defined value ‘Err… Required data not found’.

Problem: If accounts string exists, then it works perfectly. But if you remove the accounts string from the source file, Its not working as defined. Yes, if you add -not switch if ($tar1::isemptyornull) then it works again.

Can you please guide me, what is the issue.

Regards,
Roy.

I think I’m not following your need - as-is, if the value exists, then you’re not outputting $targ1? Or is the problem that you’re never branching to the “Err… Required data not found” part?

This is not valid syntax:

$tar1::isemptyornull

What you’re looking for is:

[string]::IsEmptyOrNull($tar1)

Or, alternatively for an if statement:

if (!$tar1) {}

(since both an empty string and a $null value will coerce to $false)

Hi Don,

1st thing want to mention, you are my Guru for PowerShell. Whatever I know about PS, I learnd from you.

Now coming back to the topic. This post was not showing in forum after I published. So created another post with almost same heading and following are the details. Joel and JS rectify the issue, and there was some mistakes in if else statement, which I recover. Now its working fine as expected.

This is the same topic I created earlier.
https://powershell.org/forums/topic/if-else-not-working-as-expected/

This is the corrected statement, which is working now.

$tar1=(Select-String -Pattern accounts -Path C:\type.txt).line
if (-not $tar1) {

$tar1= ‘Err… Service Account Issue, Unable to perform Target Connectivity Test’

} else {

$tar1=(Select-String -Pattern accounts, performing, “done test list operation” -Path C:\type.txt).line.trim()

}

Regards
Roy.