ScriptMonkey
ScriptMonkey

Reputation: 311

Powershell turn strings into array with headings

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
}

Upvotes: 1

Views: 14875

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

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'

Upvotes: 2

Related Questions