Brandon had this in some of his maintenance plan code and I found myself using it a bit so I thought I’d blog about it. Here is a simple script that reads a file (C:\scripts\maintenanceplans\$sqlversion\template.dtsx), replaces certain placeholders (in this case, [SERVERNAME] and [BACKUPPATH]), then writes a new file with that content.
$serverName = "sqlserver1"
$backupPath = "D:\dbbackups"
# Read in the maintenance plan template and replace the place holders
$textTemplate = [IO.File]::ReadAllText(".\maintenanceplans\$sqlVersion\template.dtsx")
$textTemplate = $textTemplate.Replace("[SERVERNAME]","$serverName")
$textTemplate = $textTemplate.Replace("[BACKUPPATH]","$backupPath")
# Write the new package. MUST use UTF8 encoding or it will break.
Set-Content -Encoding utf8 ".\out.dtsx" $textTemplate
This particular script writes out XML files. If you are writing a plain text file, remove “-Encoding utf8” and you’re set.