Adding multiple rows of data to an Object/Hash table

Tagged: ,

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Stephen Owen Stephen Owen 1 year, 12 months ago.

  • Author
    Posts
  • #21091
    Profile photo of Shane Snyder
    Shane Snyder
    Participant

    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
        $obj
      
    }
    
    
    

    Thanks,
    Shane

  • #21093
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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
    Profile photo of Stephen Owen
    Stephen Owen
    Participant

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

You must be logged in to reply to this topic.