Search code examples
powershellpowershell-3.0powershell-4.0powershell-5.0

Converting file text to Hashtable and reading value using keys?


So I have a file that looks like :

A=www.google.com
B=www.yahoo.com

Now, I want to convert this text file to a HashTable and read values using keys ie A or B

This is what I have come up with:

$hash = Get-Content .\test.txt
$hash[1].Split('=')[1]

The above script works fine except that I want to use key instead of number

Something like :

$hash['B'].Split('=')[1]

Solution

  • You will need to convert the file data into a hashtable object first. There are several techniques to add data to a hashtable object. The following will convert all lines to a hash table value provided they have the format key=value.

    $hash = [ordered]@{}
    Get-Content test.txt | Foreach-Object {
        $key,$value = ($_ -split '=',2).Trim()
        $hash[$key] = $value
    }
    
    # Value Retrieval syntax
    $hash.A
    $hash['A']
    

    If you want to target a specific line in the file, you can do the following:

    $hash = [ordered]@{}
    $data = Get-Content test.txt
    $temp = $data[1] -split '=' 
    $hash[$temp[0]] = $temp[1]
    
    # Value Retrieval Syntax
    $hash.B
    $hash['B']
    

    You could technically convert the file data with two commands, but the order may vary. I'm not sure if ConvertFrom-StringData is favorable anymore.

    $hash = Get-Content test.txt -Raw | ConvertFrom-StringData
    
    # Value Retrieval Syntax
    $hash.B
    $hash['B']
    

    Output From First Code Snippet:

    Get-Content test.txt
    A=www.google.com
    B=www.yahoo.com
    
    $hash = [ordered]@{}
    Get-Content test.txt | Foreach-Object {
        $temp = ($_ -split '=').Trim()
        $hash[$temp[0]] = $temp[1]
    }
    $hash
    
    Name                           Value
    ----                           -----
    A                              www.google.com
    B                              www.yahoo.com
    
    $hash['B']
    www.yahoo.com