It's an array, so you're looking for Count to test for contents.
I'd recommend
$foo.count -gt 0
The "why" of this is related to how PSH handles comparison of collection objects
Answer from Taylor Bird on Stack OverflowIt's an array, so you're looking for Count to test for contents.
I'd recommend
$foo.count -gt 0
The "why" of this is related to how PSH handles comparison of collection objects
You can reorder the operands:
$null -eq $foo
Note that -eq in PowerShell is not an equivalence relation.
hashtable - How to check if an associative array is empty in powershell - Stack Overflow
What's the Value of an Empty Array?
System.Collections.Generic.List - What is the proper method for checking if a generic list of objects is null or empty?
powershell - Check for empty value in Array - Stack Overflow
That's not an associative array, it's a regular array, but the answer is the same. Use .Count and compare to 0.
An associative array is called a [hashtable] in PowerShell and its literal form uses @{} (curly braces).
@{}.Count -eq 0 # hashtable (associative array)
@().Count -eq 0 # array
Arrays have Count property, and you can check if this value is 0. So the condition you would check for is
$a.Count -eq 0
You can just try
$SkippedFiles = @()
if ($SkippedFiles) {
Write-Host 'Not empty'
}
else {
Write-Host 'Empty arrays'
}
IF will check if it is null or empty
Why are you trying to differentiate? Either way the array is empty.
Its an array, so you’re looking for Count to test for contents.
Maybe I’m not understanding correctly, sorry.
I’m having a problem with the error routines I’m trying to rewrite for some scripts. The error codes are captured to arrays, and then used as parameters in if statements for reporting. If there are errors, then all is fine, but if everything works OK in the processes, the reporting errors out. I think I’ve determined that the problem is the way I’m testing the arrays, but I’m not sure. I came up with this quick script to test the value of an empty array, and it leads me to believe there’s something special about an empty array.
$SkippedFiles = @()
if ($SkippedFiles -eq 0)
{
Write-Host 'Empty arrays = 0'
}
elseif ($SkippedFiles -eq $null)
{
Write-Host 'Empty arrays = $null'
}
else
{
Write-Host 'Empty arrays are neither $null nor 0'
}
The answer I get is (you guessed it)
Empty arrays are neither $null nor 0
So just what is the value of an empty array and how do you test for it?
As the title states, what is the best/correct/preferred method for checking if a System.Collections.Generic.List of Objects is null or empty?
Do you just use Count?
If Count returns 0 then it’s empty?
I did some research and it wasn’t clear to me what the best approach was. Any advice/direction you can give would be greatly appreciated.
Thanks in advance!
The reason why I wanted to do this was kind of dumb and convoluted, I'm still curious though.