One thing I did reluctantly give up by using PSAKE was the template expansion features Derick put into Albacore. After a fairly thorough search I found that no one had a decent solution or they were keeping their find to themselves. The solutions that I did find required a bit of XML which I was aggressively staying away from. With shortage of time I had to make my own.
For my solution I chose to follow Derick’s choice of YAML files for the template data files and how these keys are represented in the templates. To me this is a more understandable format and I had most of my templates setup to use Albacore already. In case you are not familiar with how Albacore’s expandtemplates work:
Your template data file details key value pairs in YAML format.
value_1: this is some value value_2: this is another value
Your template file would represent these like :
If the process works correctly, you end up with:
What you are here for
The first step was getting the key value pairs in a usable format. To do this you have to read the data file and create a hashtable from each line. This is how you accomplish this in Powershell:
$data_values = @{}
foreach($line in $template_data) {
$d= $line.IndexOf(":")
$length = $line.Length
$data_values.add($line.Substring(0,$d).Trim() ,
$line.Substring($d+1, ($length-($d+1))))
}
Once the data file has been hashed, you need to read the contents of the file and perform the replacements:
[string] $template_text = [System.IO.File]::ReadAllText($template_file)
if ($debug -eq $true) {
echo $template_text
echo ""
echo "--------------------------------------------"
echo ""
echo "Replacing values"
}
foreach ($item in $data_values.Keys) {
if ($template_text -eq $null) {
throw "There is a problem with text template"
}
if ($debug -eq $true) {
echo " -- #{$item} with " $data_values.Get_Item($item)
}
$template_text = $template_text.Replace("#{$item}",
$data_values.Get_Item($item).Trim())
}
Finally you create the destination file:
$template_text | sc -path $destination_file