I\'m trying to get our T4 templates to run at build time, without adding dependencies on the Visual Studio Modeling SDK. I\'ve successfully used a variant of the batch file
Based on piers7 code.
Powershell script Transform.ps1
:
Param(
[string]$variablesPath,
[string]$t4File,
[string]$targetfile
)
# Get C:\Program Files (x86)\Common Files
$commonProgramFiles32 = $env:CommmonProgramFiles
if (Test-Path environment::"CommonProgramFiles(x86)") { $commonProgramFiles32 = (gi "Env:CommonProgramFiles(x86)").Value };
# Get path t4 transformer executable
$t4 = Resolve-Path "$commonProgramFiles32\Microsoft Shared\TextTemplating\14.0\texttransform.exe";
# File object for the $t4 file (.tt)
$template = (get-item $t4File)
# Create a dictionary from the contents of system variables file
$vars = @{}
get-content $variablesPath | Foreach-Object {
$split = $_.split("=")
$vars.Add($split[0], $split[1])
}
# Temp file name to store the modified template.
$templateTemp = Join-Path ([IO.Path]::GetTempPath()) $template.Name;
# Read the content of the template
$content = [IO.File]::ReadAllText($template.FullName)
# Replace the variables in the template with the actual values.
($vars.Keys | Foreach-Object {
$content = $content.Replace("`$($_)",$vars[$_])
})
# Write the modified template to the original location
$content > $templateTemp
# Execute the transformation, and delete the temporary template after done.
try{
& $t4 $templateTemp -out $targetfile -I $template.DirectoryName;
}finally{
if(Test-Path $templateTemp){ Remove-Item $templateTemp; }
}
# texttransform.exe seems to be messing up the BOM of the file. Fixing.
[IO.File]::WriteAllText($targetfile, [IO.File]::ReadAllText($targetfile), [System.Text.Encoding]::UTF8)
Then from the pre-build event:
pushd $(ProjectDir)
if exist "$(ProjectDir)var.tmp.txt" del "$(ProjectDir)var.tmp.txt"
echo SolutionDir=$(SolutionDir)>>"$(ProjectDir)var.tmp.txt"
echo ProjectDir=$(ProjectDir)>>"$(ProjectDir)var.tmp.txt"
if exist "$(ProjectDir)my.cs" del "$(ProjectDir)my.cs"
Powershell.exe -ExecutionPolicy Unrestricted -File "..\..\..\Transform.ps1" "$(ProjectDir)var.tmp.txt" "$(ProjectDir)My.tt" "$(ProjectDir)My.cs"
if exist "$(ProjectDir)var.tmp.txt" del "$(ProjectDir)var.tmp.txt"
popd