1

I am searching for a string ($Loan_Id) in a file ($File_LoanData). I am able to find it, but should the string not be found, I need the script to continue. That does not seem to be working. Here is the problem line -- if ($Note_Line -eq $false) {Continue}

$Fie_LCExtract = "c:\temp\Fie_LCExtract.txt"
$File_LoanData = "c:\temp\File_LoanData.txt"
$File_LoanDataToday = "c:\temp\File_LoanDataToday.txt"
$r = [IO.File]::OpenText($Fie_LCExtract)
while ($r.Peek() -ge 0) 
    {
     $Note = $r.ReadLine()
     $Loan_Id = ($Note -split ';')[0].trim()
     $Loan_Id = $Loan_Id -as [int]
     if (($Loan_Id -is [int])  -eq $false) {Continue}
     $Note_Line = Select-String -Path $File_LoanData -Pattern $Loan_Id
     if ($Note_Line -eq $false)   {Continue}
     $Note_Line =  ($Note_Line -split ':')[3].trim()
     $Note_Line  >> $File_LoanDataToday
   }

1 Answer 1

2

Don't compare to $False, use the return value directly as if it were a Boolean:

if (-not $Note_Line) { Continue }

Alternatively, compare to $null:

if ($null -eq $Note_Line) { Continue }

Or use the .Count property:

if ($Note_Line.Count -eq 0) { Continue }

Select-String returns a "null collection" ("nothing") when it finds no matches and this special value ([System.Management.Automation.Internal.AutomationNull]::Value) is "falsy" in a Boolean context; also, it is considered equal to $null and its .Count property is always 0.

However, despite a null collection implicitly being considered $False, comparing it explicitly to $False does not yield $True:

The null collection is treated like $null in an expression context, and the only value that $null equals (-eq) is $null itself[1].

$null -eq $False # !! $False
$null -eq $null  # $True

Using a null collection / $null implicitly as a Boolean is equivalent to casting it to [bool], so we can see that it is "falsy":

[bool] $null  # $False

[1] This applies to using $null as the LHS of -eq. As the RHS, if the LHS is array-valued, it act as a filter and returns the sub-array of elements containing $null.
For instance, $null, 1, $null -eq $null returns a 2-element array of $null values.

Sign up to request clarification or add additional context in comments.

1 Comment

Works great. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.