user4350786
user4350786

Reputation:

Powershell Hashtable Issue

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

Upvotes: 3

Views: 236

Answers (2)

Keith Hill
Keith Hill

Reputation: 202042

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

Upvotes: 2

Mike Zboray
Mike Zboray

Reputation: 40838

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"}

Upvotes: 2

Related Questions