PowerShell script example for copying correct configs based on server machine name in multi server environment

As a complement to the previous article on Extending EPiServer MSBuild config transforms to provide server specific configuration for TCP EventReplication and Licenses I wrote a small Windows PowerShell script example on how you may copy the proper configuration files to the proper server automatically during deploy. This script is available at GitHub.

Copying files with PowerShell based on environment computer name and regex

The first thing that happens in the PowerShell script examle is gathering up a few things. The name of the current server may be retrieved by accessing computername from the evironment variable $env (3). You may want to respecify where you keep your config files (4), and where your webroot is (5), for your environment; depending on how you do your deploys.

$currentServer = $env:computername
$pathToConfigs = ".\source"
$pathToWebRoot = ".\target"

Get-ChildItem is used to retrive a list of all the files in the specified configuration directory, and the Force flag ensures that hidden files (as well as system files) are also included; in other words, if you don’t need it, it could probably be omitted. The resulting list of files is then passed on to Where-Object that looks at the Name parameter of each object and includes only those that contain the name of the current machine. Match is case insensitive in PowerShell.

$currentServerConfigFiles = Get-ChildItem $pathToConfigs -Force | Where-Object {$_.Name -match $currentServer}

Looping through the list of relevant configuration files for the current server the script then extracts the filename from each file object (9). The target filename is then constructed by removing the name of the current server from the source filename (10) replacing it with an empty string; the Replace operation is also case insensitive in PowerShell.

foreach ($sourceFile in $currentServerConfigFiles) {
  $filename = $sourceFile.ToString()
  $targetFile = $filename -Replace "$currentServer.", ""

As we only have the names of the files, we concatenate a source and a target path that is passed on to Copy-Item for copying the file; the Force flag ensures that the target file is overwritten if there already is one in it’s location.

  $source = "$pathToConfigs\$filename"
  $target = "$pathToWebRoot\$targetFile"
  Copy-Item -Force -Path $source -Destination $target
  echo "Copied config file '$source' to '$target'."
}

2 Comments

  1. Valdis Iljuconoks April 21, 2015
    • Mathias Kunto April 25, 2015