PowerShell-如果文件中不包含字符串,则继续(当cmdlet不返回任何内容时检测)
我正在文件(PowerShell-如果文件中不包含字符串,则继续(当cmdlet不返回任何内容时检测),powershell,null,comparison,Powershell,Null,Comparison,我正在文件($file\u loanada)中搜索字符串($Loan\u Id)。我可以找到它,但如果找不到字符串,我需要脚本继续。这似乎不起作用。这是问题线-- if($Note\u Line-eq$false){Continue} $Fie_LCExtract = "c:\temp\Fie_LCExtract.txt" $File_LoanData = "c:\temp\File_LoanData.txt" $File_LoanDataToday = "c:\temp\File_LoanDa
$file\u loanada
)中搜索字符串($Loan\u Id
)。我可以找到它,但如果找不到字符串,我需要脚本继续。这似乎不起作用。这是问题线--
if($Note\u 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
}
不要与
$False
进行比较,直接使用返回值,就像它是布尔值一样:
if (-not $Note_Line) { Continue }
或者,比较$null
:
if ($null -eq $Note_Line) { Continue }
或者使用.Count
属性:
if ($Note_Line.Count -eq 0) { Continue }
选择字符串
在未找到匹配项时返回“null集合”(“nothing”),并且此特殊值([System.Management.Automation.Internal.AutomationNull]::value
)在布尔上下文中为“falsy”;此外,它被认为等于$null
,其.Count
属性始终为0
然而,尽管默认将空集合视为$False
,但将其显式与$False
进行比较并不会产生$True
:
null集合在表达式上下文中被视为$null
,唯一一个$null
等于(-eq
)的值是$null
本身
将null集合/$null
隐式用作布尔值相当于将其强制转换为[bool]
,因此我们可以看到它是“falsy”:
[1] 这适用于使用
$null
作为-eq
的LHS。作为RHS,
如果LHS是数组值,它将充当过滤器并返回包含$null
的元素子数组例如,
$null,1,$null-eq$null
返回一个由$null
值组成的2元素数组。非常有效。非常感谢。@hdsouza:很高兴听到这个消息;我的荣幸。我能给你推荐一下答案吗?
$null -eq $False # !! $False
$null -eq $null # $True
[bool] $null # $False