Created
February 27, 2018 15:54
-
-
Save taco-shellcode/48b1df61762402fd72e473ef35806030 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Resolve-DatabindObject { | |
param( | |
[parameter(Mandatory=$True)] | |
[string]$bindpath, | |
[parameter(Mandatory=$True)] | |
[object]$obj | |
) | |
#get token from path | |
if ($bindpath -match '^[^.]*') { | |
$token = $matches[0] | |
# pop token from path | |
if ($bindpath.IndexOf('[') -ne -1) { | |
$bindpath = $bindpath -replace (($token -replace '\[', '\[') -replace '\]', '\]') | |
} else { | |
$bindpath = $bindpath -replace $token | |
} | |
if ($bindpath[0] -eq '.') { | |
$bindpath = $bindpath.substring(1) | |
} | |
# get indexer from token | |
$index = $null | |
if ($token -match '\[[^\]]*\]') { | |
$index = $matches[0] | |
$index = ($index -replace '[\[\]]') -replace ('\"') | |
} | |
# get property from token | |
$property = $null | |
if ($token -match '^[^\[]*') { | |
$property = $matches[0] | |
} | |
if ($property -ne $null) { | |
if ($obj.contains($property)) { | |
$data = $null | |
# get value from obj | |
if ($token.IndexOf('[') -ne -1) { | |
$data = $obj[$property][$index] | |
} else { | |
$data = $obj[$property] | |
} | |
# if value is a script block, call inst | |
if ($data.gettype() -eq [ScriptBlock]) { | |
$data = Invoke-Command $data | |
} | |
if ($bindpath -eq '') { | |
# no more path, return data | |
return $data | |
} else { | |
# path continues, keep | |
return Resolve-DatabindObject $bindpath $data | |
} | |
} | |
} | |
} | |
return $null; | |
} | |
function Format-BoundTemplate() { | |
param( | |
[parameter(Mandatory=$True)] | |
[string]$template, | |
[parameter(Mandatory=$True)] | |
[hashtable]$data | |
) | |
if (-not $data) { | |
return $template | |
} | |
$buffer = $template; | |
$bindPathsRegex = New-Object System.Text.RegularExpressions.Regex('\{{[^{}]*\}}', [System.Text.RegularExpressions.RegexOptions]::Multiline) | |
$bindingPaths = $bindPathsRegex.Matches($buffer) | |
$bindingPaths | ForEach-Object { | |
$token = $_.Value | |
if ($token -and $buffer.IndexOf($token) -ne -1) { | |
$value = Resolve-DatabindObject ($token -replace "[{}]") $data | |
# escape square brackets | |
$token = ($token -replace "\[", "\[") -replace "\]", "\]" | |
# replace token with bound data | |
$buffer = $buffer -replace $token, $value | |
} | |
} | |
return $buffer; | |
} | |
Export-ModuleMember -Function * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment