Adding multiple rows of data to an Object/Hash table

Welcome Forums General PowerShell Q&A Adding multiple rows of data to an Object/Hash table

This topic contains 2 replies, has 3 voices, and was last updated by

3 years, 10 months ago.

  • Author
  • #21091

    Points: 0
    Rank: Member

    The code below first gets a list of server names from a text file. It then loops through that list grabbing a date/time stamp that is inside of another text file that is located on each of those servers.

    I am trying to build an object that contains two properties: 'Server' and 'Datetime'. I would then like to add the server name and the date/time info that is collected from each loop iteration to the object. So far I can only add a single row to the object. How can I add multiple rows to it? Does the hash table created before need to contain the multiple rows of data before making it into an object?

    $servers = Get-Content ".\servers.txt"
    $datetime_stamps = @()
    foreach($server in $servers){
        $datetime_stamps += Get-Content "\\$server\info.txt"
        $props = @{
                    'Server' = $server;
                    'DateTime'  = $datetime_stamp
        $obj = New-Object -TypeName PSObject -Property $props


  • #21093

    Points: 3
    Rank: Member

    You don't. An object is a "row," and only one.

    For example, when you run Get-Service, it outputs multiple objects to the pipeline, not one object with many 'rows.' So, you'd want to do the same thing: write each object to the pipeline (which you're doing). That would allow your script to be piped to other commands. For example, ".\My-Script.ps1 | Export-CSV" would write your multiple objects to a CSV file.

    Now, if I'm understanding you correctly, you're saying you may have multiple timestamps per server? That's fine – just do what you've done, more or less. A property of an object can itself be a collection of objects. The only thing I see wrong in your example is that you used $datetime_stamp instead of $datetime_stamps.

  • #21100

    Points: 0
    Rank: Member

    You just need to change = to += on line 11!

The topic ‘Adding multiple rows of data to an Object/Hash table’ is closed to new replies.