mao
7/3/2017 - 2:19 PM

Powershell function which reads hashtable text representation from file and converts it to hashtable object

Powershell function which reads hashtable text representation from file and converts it to hashtable object

#  .SYNOPSIS
#       Reads and evaluates Hastable object from file
#
#  .DESCRIPTION
#       Reads and evaluates Hastable object from file. As example you can read Module manifest 
#       file (*.psd1) as Hashtable object
#
#  .EXAMPLE
#       PS C:> Get-Module | Where { [IO.Path]::GetExtension($_) -match '.psd1' } |
#              Select -Last 1 | 
#              ConvertFrom-TextToHashtable | Tee-Object -Variable HashT
#       

Function ConvertFrom-TextToHashtable {
    ($Input + $Args) |
        Out-String | 
        Invoke-Expression 
}



# Invoke as follows:       & ${Get hashtable from file} '.\awesome Hashtable.txt'

${Get hashtable from file} = { PARAM($file)
    Get-Content $file | 
      ConvertFrom-TextToHashTable 
}




# Invoke as follows:       
#      & ${Import hashtable from file} '.\awesome Hashtable.txt' 'myVar'
#      Write $myVar.userData 

${Import hashtable from file} = { PARAM($file, $VarName)
  & ${Get hashtable from file} $file |
        Tee-object -Variable $VarName
}