Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Hashtable Issue

Tags:

powershell

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

1 Answers

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"}
like image 146
Mike Zboray Avatar answered Mar 28 '26 01:03

Mike Zboray