Home > Software engineering >  Convert an Array into a Hashtable Powershell
Convert an Array into a Hashtable Powershell

Time:06-27

I have an array that looks like:

 $items = @("Title    : 123456 
 field_1  : User One 
 field_2  : User 
 field_3  : One 
 field_4  : 26 
 field_5  : J123456")

However, I need the values to be in a hashtable for it to be accepted by the add-pnplistitem command. How do I convert this table into a Hashtable and be accepted by the PNP powershell command?

Thank you in advance!

CodePudding user response:

Sage Pourpre's helpful answer shows how to parse your multi-line string line by line into an ordered hashtable, which preserves the order of the key-property values as encountered in the input string.

A simpler alternative that does not preserve the entry order, however, is to use the ConvertFrom-StringData cmdlet, which requires replacing the : separators in your input with = in order to make the cmdlet recognize the input lines as key-value pairs:

$items = @("Title    : 123456 
 field_1  : User One 
 field_2  : User 
 field_3  : One 
 field_4  : 26 
 field_5  : J123456")

ConvertFrom-StringData ($items -join "`n" -replace ':', '=')

Note:

  • -join "`n" joins the elements of the array with newlines to form a single, multi-line string to pass to ConvertFrom-StringData; in your case, given that there's only one element, that one element (which is a multi-line string itself) is returned as-is.

  • As zett42 points, out, ConvertFrom-StringData treats \ as the escape character, so if verbatim \ are in your input, you'd have to double them first, with -replace '\\', '\\' (sic).

Output (a [hashtable], with unordered entries):

Name                           Value
----                           -----
field_3                        One
field_4                        26
field_2                        User
Title                          123456
field_1                        User One
field_5                        J123456

CodePudding user response:

You don't have an array of elements, what you have is a single string within an array. All those elements are parts of the same item.

Therefore, you need to split the string into lines, then into their delimiter, remove the trailing spaces and build your hashtable.

# This is an array containing 1 string.
$items = @("Title    : 123456 
 field_1  : User One 
 field_2  : User 
 field_3  : One 
 field_4  : 26 
 field_5  : J123456")

# Note, I used the Ordered keyword. This is only needed if you want to # 
# preserve the order of the elements within your original string
$MyHashtable = [Ordered]@{}
$items -split "`r?`n" | ForEach-Object { 
    $el = $_.split(':') 
    $Key = $el[0].Trim()
    $MyHashtable.$key = $el[1].trim()
}

# Output your hashtable
$MyHashtable
  • Related