Parameterizing Scripts with PowerShell Data Files

In my previous blog I introduced the Get-Blacklist function which turned a string array into a hashtable for quick comparisons:

function Get-Blacklist {
	param(
		[string[]]$Blacklist
	)
	$blacklistHash = @{}
	$Blacklist | % {
		$blacklistHash[$_] = $true
	}
	$blacklistHash
}

and invoked it thus:

. .\Scripts\Get-Blacklist.ps1
@blacklist = Get-Blacklist -Blacklist 'Powershell','Sandbox','sqlccJamie','Graphics','CentinelTest','Backoffice Service Portal'

As a rule I prefer not to embed literal constants like this in my scripts, especially as they go into production. Values like these are prone to change much more than the pure code, and will likely be maintained in future by administrators with little PowerShell experience.

There are many configuration file formats that PowerShell handles well, but the PowerShell Data File format is particularly useful. It is the format used for module manifests, i.e. .psd1 files. Here is one for the blacklist:

@{
    # Team Blacklist - Teams not to be sychronized between NuGet servers
    TeamBlacklist = @('Powershell','Sandbox','sqlccJamie','Graphics','CentinelTest','Backoffice Service Portal')
}

I’ll be adding more than one of these, hence the longer name. We need to import it before we can use it:

$par = Import-PowerShellDataFile -Path "$PSScriptRoot\SyncPackages.psd1"

# Get Azure DevOps project and repos
$repoNames = Get-RepoNames -Blacklist $par.TeamBlacklist

There we go!

I made use of the built-in variable $PSScriptRoot pointing to the script being executed. It was introduced in PowerShell 3.0.