Powershell null value

asif ahamed 201 Reputation points
2023-04-25T22:38:00.47+00:00

(get-process | select-object ProcessName,Id,WS -First 1).count - > null this comes null why is that? if I put @(get-process | select-object ProcessName,Id,WS -First 1).count - > 1 My second issue is when I run @($y.entries.values).count - > 1 (This is wrong) but when I run $y.entries.values - > Comes null (this is correct) @($y.entries.values).count must be null NOT 1 Why?

@($null).count =1 - > when I calculate if it is null then it comes 1

Please help me

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2023-04-26T01:48:13.9866667+00:00

    When you run (get-process | select-object ProcessName,Id,WS -First 1).count the Select-Object picks the first object from the pipe. Because there's only one object the result is a scalar value, not an array, and scalars don't have a "count" property.

    When you place the "@" sigil in front of the parentheses you're coercing the result to be an array. Arrays have a "count" property so you'll get the answer you expected. In your other example, the $y.entries.values property is probably a null value. The value "$null" has no "count" property. When you use the "@" sigil you will get an array with a single element whose value is $null. Again, an array has a "count" property.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. asif ahamed 201 Reputation points
    2023-04-26T02:30:38.72+00:00
    I wrote a function to resolve this
    
    Function ValueORzero
            {
                param (
                    $myVal
                )
                if (![string]::IsNullOrEmpty($myVal))
                {
                    $res=($myVal.count)
                }
                else
                {
                    $res=0
                }
                return $res 
            }
            
            $answer=ValueORzero ($x.entries.values)
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.