3

I create a small script for accepting a Users ID, First Name, Last Name and then adding that data to a hash table. The problem I have is when I display my hashtable to says the value of the user is System.Object. What am I doing wrong?

$personHash = @{}
$userID=""
$firstname=""  
$lastname=""


    While([string]::IsNullOrWhiteSpace($userID))
    {
        $userID = Read-Host "Enter ID"
    }

    While([string]::IsNullOrWhiteSpace($firstname))
    {
        $firstname = Read-Host "Enter First Name"
    }


    While([string]::IsNullOrWhiteSpace($lastname))
    {
        $lastname = Read-Host "Enter Last Name"
    }


$user = New-Object System.Object
$user | Add-Member -type NoteProperty -Name ID -value $userID
$user | Add-Member -type NoteProperty -Name First -value $firstname
$user | Add-Member -type NoteProperty -Name Last -Value $lastname
$personHash.Add($user.ID,$user)

$personHash
5
  • You create $user as a System.Object. What are you expecting? Commented Dec 13, 2014 at 18:58
  • Try $personHash[$user.ID] or $personHash['NameYouEntered']. You see System.Object because the hashtable contains an object of that type as the value for that entry. It's a placeholder that says "There's an object here, but it's too complex to display." Commented Dec 13, 2014 at 18:59
  • @BaconBits - How do I correct this user to show my user object properly? Commented Dec 13, 2014 at 19:00
  • In a hashtable? You don't. Not with the way you're doing the object. Commented Dec 13, 2014 at 19:01
  • @BaconBits - I think mike z provided the correct answer. Commented Dec 13, 2014 at 19:03

2 Answers 2

2

It looks like when PowerShell displays the contents of a hashtable it just calls ToString on the objects in the table. It doesn't format them using the DefaultDisplayPropertySet as it usually does.

One alternative is to use PSCustomObject instead of System.Object like so:

$user = New-Object PSCustomObject -Property @{ ID = $userID; First = $firstname; Last = $lastname }
$personHash.Add($user.ID, $user)

Then the display will be something like:

Name         Value  
----         -----  
1            @{ID=1;First="Mike";Last="Z"}
Sign up to request clarification or add additional context in comments.

1 Comment

There's no need to use new-object here. You can merely cast the hashtable to [PSCustomObject].
2

Use [PSCustomObject] to create at type that PowerShell knows how to render to string:

$personHash = @{}
$userID=""
$firstname=""  
$lastname=""

While([string]::IsNullOrWhiteSpace($userID))
{
    $userID = Read-Host "Enter ID"
}

While([string]::IsNullOrWhiteSpace($firstname))
{
    $firstname = Read-Host "Enter First Name"
}

While([string]::IsNullOrWhiteSpace($lastname))
{
    $lastname = Read-Host "Enter Last Name"
}

$personHash[$userID] = [pscustomobject]@{ID=$userID; First=$firstname; Last=$lastname}
$personHash

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.