I'm trying to parse an un-structured array into columns when that array is missing delimiters. The way the array looks from a data operation after inputted into a text file is below:
DC1
49600 Reachable
49601 Reachable
49602 Reachable
49603 Reachable
49604 Reachable
49605 Reachable
49606 Reachable
49607 Reachable
DC2
49600 Reachable
49601 Reachable
49602 Reachable
49603 Reachable
49604 Reachable
49605 Reachable
49606 Reachable
49607 Reachable
The data array inside the an HTML email looks like this:
Screenshot #1:
I need it to be two columns instead, like this:
Screenshot #2:
What I've tried is a few things, first, assigning the array to a variable, $Result. I then out-file that to a text file and then email $Result in the body of an HTML email. What winds up happening is the email body looks like the blob of text in Screenshot #1. I then tried various "join" statements in various combinations to even worse results. After banging my head for several hours, I've decided to post here.
EDIT: Changed Subject line of question and the parts of the question where I mentioned strings - we are talking about arrays here, not strings. (Thanks Santiago)
CodePudding user response:
The code is awfully complicated but should get you what you need. As you can see, it should work with multiple DCxx
.
Note: The Here-String @'...'@
is there just as an example to test the code, if this is read from a file, be sure to use the -Raw
switch of Get-Content
.
$result = [ordered]@{}
@'
DC1
49600 Reachable
49601 Reachable
DC2
49602 Reachable
49603 Reachable
49604 Reachable
49605 Reachable
49606 Reachable
49607 Reachable
DC3
49600 Reachable
49601 Reachable
49602 Reachable
DC4
49603 Reachable
49604 Reachable
49605 Reachable
49606 Reachable
49607 Reachable
'@ -split '\b(?=DC\d )\b' -ne '' | ForEach-Object {
$parse = ($_ -split '\r?\n' -ne '').ForEach('Trim')
$header = $parse[0]
$data = $parse[1..($parse.Count - 1)]
$result.Add($header, $data)
}
$maxIter = $result.Keys.ForEach({$result[$_].Count}) | Measure-Object -Maximum
$toHTML = for($i = 0; $i -lt $maxIter.Maximum; $i )
{
$out = [ordered]@{}
foreach($key in $result.Keys)
{
$out.Add($key, $result[$key][$i])
}
[pscustomobject]$out
}
$style = @'
<style>
* {
font-family: Calibri, sans-serif;
padding: 0px;
margin: 0px;
text-align: left;
}
table {
border-collapse: collapse;
width: 50%;
font-size: 13px;
margin: 10px;
}
th {
background-color: #708090;
color: white;
font-size: 16px;
font-weight: bold;
padding: 5px 5px 5px 15px;
text-align: left
}
td {
padding: 5px 5px 5px 15px;
}
tr:nth-child(odd) {
background-color: #f2f2f2;
}
</style>
'@
$toHTML | ConvertTo-Html -PreContent $style | Out-File ./test.html
Invoke-Item ./test.html