Why can not I get Select-Object to work on hashtable right

This topic contains 4 replies, has 4 voices, and was last updated by  Max Kozlov 2 years ago.

  • Author
    Posts
  • #28875

    GS
    Participant

    I have hashtable which is returned from execution of remote command. Yet when I issue Select-Object command it does not pull those properties out. It does work on some objects and not on others (I execute the same script on range of computers). And I can not figure out what the difference between those.


    PS C:\> $b.GetType()

    IsPublic IsSerial Name BaseType
    -------- -------- ---- --------
    True True Hashtable System.Object

    PS C:\> $b.Keys
    LogNameForSource
    MachineName
    SourceExists
    PS C:\> $b.Values
    Application
    DNVAPPSVC1
    True
    PS C:\> $b | Select-Object -Property LogNameForSource, MachineName, SourceExists | ft -AutoSize

    LogNameForSource MachineName SourceExists
    ---------------- ----------- ------------

  • #28876

    GS
    Participant

    I found what the difference is – one some computers using Invoke-Command returns PSCustomObject and on others it returns HashTable code is below


    $temp = {$result= [pscustomobject]@{"MachineName" = $env:ComputerName; "SourceExists" = [bool] $false;"LogNameForSource"=""}
    if ([System.Diagnostics.EventLog]::SourceExists('dcom'))
    {
    $result.SourceExists = $true
    $result.LogNameForSource = [System.Diagnostics.EventLog]::LogNameFromSourceName("dcom", ".")
    }
    return $result
    }

    $a = Invoke-Command -ScriptBlock $temp -ComputerName Server1
    PS C:\> $a.GetType().Name
    PSCustomObject
    $a = Invoke-Command -ScriptBlock $temp -ComputerName Server2
    PS C:\> $a.GetType().Name
    Hashtable

  • #28878

    Don Jones
    Keymaster

    And a hash table only has Key and Value properties. You can't select just a particular key using Select-Object.

  • #28880

    Daniel Krebs
    Moderator

    GS,

    Check out the official documentation regarding hash tables for examples:

    https://technet.microsoft.com/en-us/library/Hh847780.aspx

  • #28901

    Max Kozlov
    Participant

    GS, on these computers you probably does not have latest PS

    PS C:\Users> $psversiontable
    Name Value
    ---- -----
    [...]
    PSVersion 2.0
    [...]
    PS C:\Users> [pscustomobject]@{aaa='aaaa';bbb='bbbb'}
    Name Value
    ---- -----
    bbb bbbb
    aaa aaaa
    PS C:\Users> ([pscustomobject]@{aaa='aaaa';bbb='bbbb'}).gettype()
    IsPublic IsSerial Name BaseType
    -------- -------- ---- --------
    True True Hashtable System.Object

    [pscustomobject] was implemented on v3+

You must be logged in to reply to this topic.