Various `$ null` in PowerShell

I have two functions:

function test1 {
  $tmp = "1", "2", "3"
  $a = $tmp | Where-Object {$_ -match "4"}
  $b = $tmp | Where-Object {$_ -match "4"}
  return $a,$b
}

function test2 {
  $tmp = "1", "2", "3"
  $a = $tmp | Where-Object {$_ -match "4"}
  $b = $tmp | Where-Object {$_ -match "4"}
  if($a -eq $null) { $a = $null }
  if($b -eq $null) { $b = $null }
  return $a,$b
}

(test1)[0] -eq $null produces the following error:

Cannot index into a null array.
At line:1 char:1
+ (test1)[0] -eq $null
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : NullArray

while (test2)[0] -eq $nullreturns True.

Can someone explain to me why this is happening? I am using PowerShell 4.0.

+4
source share

Source: https://habr.com/ru/post/1605644/


All Articles