Hashtable Powershell issues

I am creating a small script to accept a user id, first name, last name, and then add that data to a hash table. The problem I am having is when I show my hash table saying the user value 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

      

+3


source to share


2 answers


It looks like when PowerShell displays the contents of the hash table, it just calls ToString on the objects in the table. It does not format them using the DefaultDisplayPropertySet

usual way.

One option is to use PSCustomObject instead of System.Object, for example:

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

      



Then the display will show something like:

Name         Value  
----         -----  
1            @{ID=1;First="Mike";Last="Z"}

      

+2


source


Use [PSCustomObject]

to create in a type that PowerShell knows how to render a 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

      

+2


source







All Articles