Skip to content

Instantly share code, notes, and snippets.

@andrewthauer
Last active March 22, 2021 06:28
Show Gist options
  • Save andrewthauer/4c3ea49b2f0da9f906fb3ea9b02e59ba to your computer and use it in GitHub Desktop.
Save andrewthauer/4c3ea49b2f0da9f906fb3ea9b02e59ba to your computer and use it in GitHub Desktop.
PowerShell Script - Update Env Variables in Files
# Replace-Vars script
#
# Description:
# Replaces varibles in the specified files
#
# Usage:
# Replace-Vars.ps1 [files_to_update_array] [config_vars_hash]
#
# Examples:
# ./Replace-Vars.ps1 ./file1.txt @{ API_URL = 'MY_VAR' }
# ./Replace-Vars.ps1 ./file1.txt (Get-Content -Raw "/path/to/.env" | ConvertFrom-StringData)
# ./Replace-Vars.ps1 -Files ./file1.txt,./file2.txt $config
#
param(
[String[]] $files,
[Hashtable] $config
)
$ErrorActionPreference = "Stop"
# Key to token function
# NOTE: This must match the keys in the environment
function KeyToToken($key) { "__${key}__" }
# Core function to subsitute values
function ReplaceConfigValues($file, $config)
{
$config.Keys |
ForEach-Object `
{ $accum = (Get-Content $file) } `
{ $accum = ($accum -replace (KeyToToken $_), $config[$_]) } `
{ $accum } |
Set-Content $file
}
# Get the fully qualified paths
$filePaths = @()
foreach ($file in $files) { $filePaths += $(Resolve-Path $file) }
# Starting ...
Write-Output "Started Replace-Vars - Using: $($config | ConvertTo-JSON)"
# Replace values in files
foreach ($file in $filePaths)
{
Write-Output "Updating: $file"
ReplaceConfigValues $file $config
}
# Done
Write-Output "`Finished Replace-Vars"
exit 0
# Update-AppEnv script
#
# Description:
# Updates the application environment
#
# Usage:
# Update-AppEnv.ps1 [config_hash]
#
# Example:
# $config = @{
# API_URL = 'http://api/'
# API_KEY = 'ABC'
# # ...
# }
# ./Update-AppEnv.ps1 $config
#
param(
[Hashtable] $config = $null
)
# Stop script on any error
$ErrorActionPreference = "Stop"
# Helper
function ValueOrDefault($val, $defaultVal) { if ($val -ne $null) { $val } else { $defaultVal } }
# Starting ...
Write-Output "Started Update-AppEnv ..."
# Set the current working directory
$currentDir = Split-Path -parent $PSCommandPath
Push-Location $currentDir
# Look for .env config if no config
if (!$config)
{
$envFile = (Resolve-Path "${currentDir}/../.env")
$config = (Get-Content -Raw "${envFile}" | ConvertFrom-StringData)
}
# Set default fallback values
# $config['SOME_KEY'] = ValueOrDefault $config['SOME_KEY'] '[DEFAULT_VALUE]'
# Files to replace values with
$files = @(
$(Resolve-Path "$currentDir/../dist/main.*.js")
)
# Update files
./Replace-Vars.ps1 -Files $files -Config $config
# Done
Pop-Location
Write-Output "Finished Update-AppEnv ..."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment