Hi Team,
I posted the same post 40 min ago, still its not showing so posted it again. If you found the previous post, you can ignore ny one.
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 (-not $tar1::isemptyornull) then it works again.
Yep, that’s it. The :: operator is only valid with static classes and methods, so you can only call them from the type accelerator themselves. However, if you want the ::IsNullOrEmpty() effect with that syntax, you should use:
if (-not $string) {}
To clarify the alternative js mentions, both $null and “” (empty string) values will be automatically converted to the boolean value false, which you can see if you do so manually:
[bool]$null
[bool]""
This allows you to effectively perform the “null or empty” check without bothering to invoke a specific method. I find it helps me make sense of that if statement if I think of it as more or a “if anything is in this string/variable”.
However if there is a possibility that there might be empty space in the string (i.e., it’s " “ instead of ”") then this will fail, because although a space looks empty, it’s still a character and thus the string is not empty. To cover those situations, you can also perform a check like this:
if (-not $string -or $string -match "^\s+$") {}
That will give the $true response if the string is either null, empty, or contains nothing but spaces.