1

I'd like to create a table with headings from a series of strings, which have been pulled from an output. I've already used this...

$Scopearray = @("$server","$ip","$ScopeName","$Comment")

To turn this...

$ip = $Trimmed[0]
$server = $Trimmed[1]
$ScopeName = $Trimmed[2]
$Comment = $Trimmed[3]

Into this:

PS C:\WINDOWS\system32> $Scopearray 
MyServer.domain
10.1.1.1
NameofScope
ScopeDetails

But I need to turn that into a table, something like this:

Table Example

I've tried the below, and a copule of other multidimentional examples, but I'm clearly missing something fundamental.

$table = @()
foreach ($instance in $Scopearray) {
$row = "" | Select ServerName,IP,ScopeName,Comment
$row.Heading1 = "Server Name"
$row.Heading2 = "IP Address"
$row.Heading3 = "Scope Name"
$row.Heading4 = "Comment"
$table += $row
}
1
  • Why dont you create an object inside the foreach loop and add the object to an arraylist. Declare the arraylist outside the loop. And inside the loop you can still do your trimming operation and assign that value to that object. Makes sense? Commented Aug 24, 2017 at 2:54

1 Answer 1

2

Create objects from your input data:

... | ForEach-Object {
    New-Object -Type PSObject -Property @{
        'Server Name' = $Trimmed[1]
        'IP Address'  = $Trimmed[0]
        'Scope Name'  = $Trimmed[2]
        'Comment'     = $Trimmed[3]
    }
}

In PowerShell v3 and newer you can simplify that by using the [PSCustomObject] type accelerator:

... | ForEach-Object {
    [PSCustomObject]@{
        'Server Name' = $Trimmed[1]
        'IP Address'  = $Trimmed[0]
        'Scope Name'  = $Trimmed[2]
        'Comment'     = $Trimmed[3]
    }
}

PowerShell displays objects with up to 4 properties in tabular form by default (unless the objects have specific formatting instructions), but you can force tabular output via the Format-Table cmdlet if required:

... | Format-Table

Note that you need Out-String in addition to Format-Table if for instance you want to write that tabular representation to a file:

... | Format-Table | Out-String | Set-Content 'C:\output.txt'
Sign up to request clarification or add additional context in comments.

1 Comment

For completeness, this outputs four identical values, so adding ` | select -First 1` at the end provides the exact answer, but otherwise a great solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.