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 Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, and holds a number of certifications, including those relating to SQL Server, Linux, SharePoint and network security. 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 *