locked
Create PSobject out of Array String RRS feed

  • Question

  • Lets say I have following strings in a text file

    node down|xyzserver|inc0001|/30/05/2018

    node down|abzserver|inc0002|/29/05/2018

    --------------------------------------

    I want to convert these into a PS object with 4 properties by spiting with |. I tried with below but it gives me onlt

    gc C:\test.txt | % {
    $line = $_
    $split = $line.split("|")
    
    $alertname = $split[0]
    $device = $split[1]
    $Incident = $split[2]
    $Date = $split[3]
    
    $obj = New-Object psobject
    $obj | Add-Member -NotePropertyName AlertName ($AlertName)
    $obj | Add-Member -NotePropertyName DeviceName($device)
    $obj | Add-Member -NotePropertyName Incident($Incident)
    $obj | Add-Member -NotePropertyName DateTime($Date)
    }
    $obj
    

    I tried like below too where I storred mulitple values as a aaray and then added to the note properties

    $AlertName = @()
    $device = @()
    $Incident = @()
    $Date = @()
    
    gc C:\test.txt | % {
    
    $line = $_
    $split = $line.split("|")
    
    $alertname += $split[0]
    $device += $split[1]
    $Incident += $split[2]
    $Date += $split[3]
    
    }
    
    $obj = New-Object psobject
    $obj | Add-Member -NotePropertyName AlertName ($AlertName)
    $obj | Add-Member -NotePropertyName DeviceName($device)
    $obj | Add-Member -NotePropertyName Incident($Incident)
    $obj | Add-Member -NotePropertyName DateTime($Date)
    
    $obj
    

    But the result I got is like below

    AlertName           DeviceName          Incident            DateTime           
    ---------           ----------          --------            --------           
    {Node Down, Node... {xyz, NO... {INC0001... {5/30/2018.....

    If I call an individual property like $obj.alertname then it gives me correct list but I wanted to get the list like a how output of command like Get-service looks like


    Thanks, Samer

    Wednesday, May 30, 2018 5:40 AM

Answers

  • Why not using Import-CSV like this:
    Import-Csv -Path C:\test.txt -Delimiter '|' -Header 'AlertName','DeviceName','Incident','Date'


    Best regards,

    (79,108,97,102|%{[char]$_})-join''

    • Marked as answer by Samer87 Wednesday, May 30, 2018 6:12 AM
    Wednesday, May 30, 2018 6:08 AM