ConvertString to Array

Hi All,

Can you please help me in converting below string to array. I would like to see the names before colons as column heading and the respective data as value under the column.

String:

"Name: Microsoft.SystemCenter.DataProtectionManager.Alert

AlertStringName: DPM: This is a test alert

Source: XYZ-Weekly "

Try split:

$array = 'Name: Microsoft.SystemCenter.DataProtectionManager.Alert' -split ':'

$array[0]

$array

Not so much an array as a custom object, then.

The simplest approach is to modify the string so that ConvertFrom-StringData can parse it. This means replacing the first : on every line with an = sign.

$ObjectData = $String -replace '^(?<=[^:]+):','=' | ConvertFrom-StringData

Do note that for whatever reason this forum inserts a space between the < and = characters; please remove that before use. It's not meant to be there!

That regex expression broken apart goes like this:

"
^      -- anchor to the beginning of the line
(?<=   -- lookbehind; this is used to locate the rest of the match but will not be replaced
[^:]+  -- Match any number of characters that are NOT the ':' character
)      -- End lookahead. Up to here, we're saying "ensure there are no : before this next part"
:      -- Match the ':' character (combined with the lookbehind, this will get only the first one)
"

Only the : character gets replaced, but it’s anchored to the beginning of each line such that subsequent ones aren’t touched.

Thank you Joel for your response but I’m getting error while running the code:

 

error: “The regular expression pattern ^(?< =[^:]+): is not valid”

Thank you Rob, I have two colons in a single line in my string … How to split only at the first colon?

If you split by colon, the operation applies to all colons. You can use indexing against the split result how Rob has shown in his example.

As I mentioned, make sure you remove the space from the pattern; this forum won’t let me enter the pattern correctly. The < and = should have no space between them. I rechecked it, to be sure, and there’s one other modification you need to make to the pattern.

Been a while since I had to use this, so there's a few extra steps that escape my memory.

$Hashtables = $string -split '\n' -replace '(?<=^[^\:]+)\:','=' | ConvertFrom-StringData
$Compiled = @{}
# ConvertFrom-StringData seems to make an array of hashtables, so it's a bit extra work here
foreach ($Table in $Hashtables) {
    $Compiled += $Table
}
$object = [PSCustomObject]$Compiled

It may be a little more effective to just do a complete match pattern, but that is a bit less flexible.

Thanks Joel, it’s working fine now.