Home > Software engineering >  ConvertFrom-StringData creates an array of Objects instead of a Hash-Table
ConvertFrom-StringData creates an array of Objects instead of a Hash-Table

Time:01-09

I have a text file with the following content:

K:=\\kiefs83001\digipack
O:=\\kiefs73001\sws02\digipack

and would like to put this in a Hash-Table. It seemed to work but when I try to access the values I get no result. E. g. $hash["key"] results in nothing

Here is what I did so far:

$content = get-content "textfile.txt"
# escape the Backslashes for the next step
$content = $content.Replace("\", "\\");
 
$hash = $content | ConvertFrom-StringData  # should create a Hash-Table

$hash results in:

Name                           Value
----                           -----
K:                             \\kiefs83001\digipack
O:                             \\kiefs73001\sws02\digipack

But: $hash["K:"] -> results in just a new prompt

and $hash.GetType() -> results in

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

I have been peekin' around and found a similar issue from 2 years ago but the solution - converting the objects to key/value pairs - does not work for my problem :(

$newhash = @{}
$hash | ForEach-Object {
    $newhash[$_.key] = $_.value
}

It says:

Error during indexing. The Arrayindex is NULL (roughly translated from German to English)
  $hash[$_.key] = $_.value
  ~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      FullyQualifiedErrorId : NullArrayIndex

What the heck am I doing wrong?

CodePudding user response:

Stoopid me! I just solved it the simple way:

my test.txt looks like:

g:=\\server\firstshare
k:=\\server\secondshare

my code is now

$ht = @{}
$file = Get-Content "test.txt"
foreach($line in $file){
  $arr = $line.Split('=')
  $ht.Add($arr[0], $arr[1])
}

$ht now results in:

Name                           Value
----                           -----
k:                             \\server\secondshare
g:                             \\server\firstshare

and $ht["g:"] outputs:
\\server\firstshare

and this is exactly what I need

  • Related