Format from a Variable

This topic contains 4 replies, has 3 voices, and was last updated by  David DeHerrera 3 years, 8 months ago.

  • Author
    Posts
  • #14343

    David DeHerrera
    Participant

    I am trying to format my data once I have saved it in a variable. But I am unable to figure out a way of doing this. Here is my process:

    $strComputers = "Computer1", "Computer2"
    $FailOutput = "Location, State `n"
    Foreach ($strcomputer in $strComputers)
    {
        If (!(Test-Connection -ComputerName $strComputer -Count 1 -Quiet))
        {
            $FailOutput += "$($strComputer), Is not online or exsit. `n"
        }
    }
    $FailOutput

    And here is what I get:
    Location, State
    Computer1, Is not online or exsit.
    Computer2, Is not online or exsit.

    But I would like if the computer names are not the same amount of characters, I would like everything tabbed or in a neat table.

    How would I go about doing this?

    Thank you in advance.
    David D.

  • #14344

    Don Jones
    Keymaster

    If you want PowerShell to do that for you, then you need to create a custom object instead of just outputting text.


    $properties = @{'ComputerName'=$strComputer;
    'Status'=$whatever}
    New-Object -Type PSObject -Prop $properties

    You could pipe the new object to a text file, to Export-CSV, or whatever. This is the fundamental unit of work in Windows PowerShell, so mastering object-based output is pretty much key to getting the shell to do anything for you. Check out my "Learn PowerShell Toolmaking in a Month of Lunches" book – it's based around this entire concept.

  • #14360

    David DeHerrera
    Participant

    Don, Picked up my book. I thought I knew PowerShell pretty good, but now I have been put in my place. ha

    Thank you again, I will start my read.
    David D.

  • #14345

    Bert Nieuwenampsen
    Participant


    $strcomputers = "computer1", "computer2"
    $failoutput = "location, state `n"

    foreach ($strcomputer in $strcomputers)
    {
    $test = "$($strcomputer), is online. `n"
    if (!(test-connection -computername $strcomputer -count 1 -quiet))
    {
    $test = "$($strcomputer), is not online or exsist. `n"
    }
    $failoutput += $test
    }
    $failoutput

  • #14386

    David DeHerrera
    Participant

    Just FYI, here is my final sample script, and works like a charm. Thanks again Don for the proper push.

    $strComputers = "Computer1", "Computer2"
    Foreach ($strcomputer in $strComputers)
    {
        If (!(Test-Connection -ComputerName $strComputer -Count 1 -Quiet))
        {
            $whatever = "Not Online"
            $properties = @{'ComputerName'=$strComputer; 'Status'=$whatever}
            New-Object -Type PSObject -Prop $properties
        }
    }

You must be logged in to reply to this topic.