PowerShell: Find/Replace Template

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.

Chrissy is a PowerShell MVP who has worked in IT for nearly 20 years, and currently serves as a Sr. Database Engineer in Belgium. Always an avid scripter, she attended the Monad session at Microsoft’s Professional Developers Conference in Los Angeles back in 2005 and has worked and played with PowerShell ever since. Chrissy is currently pursuing an MS in Systems Engineering at Regis University and helps maintain RealCajunRecipes.com in her spare time. She holds a number of certifications, including those relating to SQL Server, SuSE Linux, SharePoint and network security. She recently became co-lead of the SQL PASS PowerShell Virtual Chapter. You can follow her on Twitter at @cl.

Posted in PowerShell
2 comments on “PowerShell: Find/Replace Template
  1. Mark Bailey says:

    Thank you so much! This helps me a lot. It doesn’t quite function as written though, by the way. The last line of this code uses $packageContents, which is not defined, rather than $textTemplate.

Leave a Reply

Your email address will not be published. Required fields are marked *