PoshCode Logo PowerShell Code Repository

ConvertTo-PS1 by mario 3 weeks ago
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6831"></script>download | new post

Transform nested hashtable into Powershell-literal (string)

  1. # encoding: utf-8
  2. # api: ps
  3. # type: functions
  4. # category: data
  5. # title: ConvertTo-PS1
  6. # description: Transform nested hashtable into Powershell-literal (string)
  7. # version: 0.5
  8. # status: beta
  9. # license: MITL
  10. #
  11. # Workaround implementation due to lack of ConvertTo/From-Json in PS 2.0.
  12. # Useful to create a speedier cache, e.g. after extracting Excel files.
  13. # Outfiles can be read in with `$hash = (. ./data/cachefn.ps1)` simply.
  14. #
  15. #   Only covers strings, integers, and hashtables
  16. #   REALLY REALLY crude string filtering
  17. #   Just didn't want to use less legible @''@
  18. #   Definitely NOT SAFE to use on arbitrary input
  19.  
  20.  
  21. #-- Transform nested hashtable into Powershell-literal (string)
  22. function ConvertTo-PS1() {
  23.     param($hash, $indent="", $depth=100, $CRLF="`r`n", $Q="'", $v2=@{})
  24.     $sub = $indent + "    "
  25.     switch ($hash.GetType().Name) {
  26.         Int32 {}
  27.         Double {}
  28.         String { $hash = $Q + ($hash -replace "[''``&#8219;&#8219;]","") + $Q }
  29.         PSCustomObject {
  30.             $hash.PSObject.Properties | ? { $_.Name } | % { $v2[$_.Name] = $_.Value }
  31.             $hash = ConvertTo-PS1 $v2 $indent
  32.         }
  33.         Hashtable {
  34.             $hash = "@{$CRLF" + (($hash.keys | % {
  35.                 $sub + (ConvertTo-PS1 $_ $sub) + " = " + (ConvertTo-PS1 $hash[$_] $sub)
  36.             }) -join ";$CRLF") + "$CRLF$indent}"
  37.         }
  38.         default { $hash = "$Q$value$Q"; }
  39.     }
  40.     return "$hash"
  41. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me