Skip to content

Instantly share code, notes, and snippets.

@nichollsc81
Last active January 18, 2021 11:32
Show Gist options
  • Save nichollsc81/7cb16373cbe1d08ba45a4ad9e9917690 to your computer and use it in GitHub Desktop.
Save nichollsc81/7cb16373cbe1d08ba45a4ad9e9917690 to your computer and use it in GitHub Desktop.
PoSh Json File Transform
<#
.SYNOPSIS
Substitutes connection string via json connstring key.
.DESCRIPTION
Substitutes connection string via json connstring key.
.EXAMPLE
PS>$files = ('C:\TEMP\git\moneycorp\Screening.Batch\Screening.Batch.Db\appsettings.json','C:\TEMP\git\moneycorp\Screening.Batch\Screening.Batch.Api\appsettings.json').Split(',')
PS>foreach($file in $files){
PS> $Transform = @{
PS> Filepath = $file
PS> JsonKey = 'ScreeningBatch'
PS> ConnectionString = 'Data Source=.,1433;Database=ScreeningBatch;Integrated Security=false;User ID=sa;Password=Password10;'
PS> WhatIf = $false
PS> Verbose = $false
PS> }
PS> Set-ScreeningBatchConnString @Transform
PS>}
Iterates over supplied files looking ConnectionStrings.ScreeningBatch key.
Once source, replaces Connection String value with that supplied.
#>
function Set-ScreeningBatchConnString
{
[CmdletBinding(SupportsShouldProcess)]
param (
# absolute path to appsettings.json file for file transform
[Parameter(Mandatory = 'true', Position = 0)]
[ValidateNotNullOrEmpty()]
[string] $FilePath,
# json key to be replaced. E.g. ConnectionsStrings.$JsonKey
[Parameter(Mandatory = 'true', Position = 1)]
[ValidateNotNullOrEmpty()]
[string] $JsonKey,
# Connection String to replace
[Parameter(Mandatory = 'true', Position = 2)]
[ValidateNotNullOrEmpty()]
[string] $ConnectionString
)
begin
{
$ErrorActionPreference = 'Stop'
$appSettingsFile = $FilePath
$appSettingsFileName = (gi $appSettingsFile).Name
Write-Verbose "File: $($appSettingsFile)"
Write-Verbose "Key: $($JsonKey)"
}
process
{
try
{
# convert file to object
$fileFromJson = (Get-Content $appSettingsFile -Encoding UTF8 -Raw | ConvertFrom-Json)
}
catch
{
$_
Break
}
# replace parameter
if ($fileFromJson.ConnectionStrings.$JsonKey)
{
Write-Host "Detected key $($JsonKey) to update in $($appSettingsFileName)"
$fileFromJson.ConnectionStrings.$JsonKey = $ConnectionString
}
else
{
Write-Warning "No $($JsonKey) conn string key to update in $($appSettingsFileName)."
Continue
}
}
end
{
try
{
if ($PSCmdlet.ShouldProcess($appSettingsFile, 'File Transform'))
{
# update file
$outFile = ConvertTo-Json @($fileFromJson) -Depth 10 -Compress | Format-Json -Indentation 2 | Set-Content -Path $appSettingsFile -Encoding UTF8
}
Write-Host "$($appSettingsFile) transformed."
}
catch
{
$_
Break
}
}
}
### region ends
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment