Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active September 11, 2024 02:31
Show Gist options
  • Save Jaykul/37f985146e275a51060d1c3e4c74b922 to your computer and use it in GitHub Desktop.
Save Jaykul/37f985146e275a51060d1c3e4c74b922 to your computer and use it in GitHub Desktop.
Functions for powershell.config.json
#requires -Modules Metadata
function Get-PowerShellConfig {
<#
.SYNOPSIS
Get the PowerShell.config.json as a hashtable
.EXAMPLE
Get-PowerShellConfig
Returns the user's PowerShell Config (usually just what experiments you've enabled)
.EXAMPLE
Get-PowerShellConfig -Scope Machine
Returns the Machine (or AllUsers) PowerShell Config
#>
[CmdletBinding()]
param(
# Which config file to read
[ValidateSet("User","Machine","CurrentUser","LocalMachine")]
$Scope = "User"
)
$Path = if ($Scope -match "User") {
Join-Path (Split-Path $Profile) powershell.config.json
} else {
Join-Path $PSHOME powershell.config.json
}
Write-Information $Path
if (Test-Path $path) {
Get-Content $path | ConvertFrom-Json -AsHashtable
} else {
@{}
}
}
function Set-PowerShellConfig {
<#
.SYNOPSIS
Set values in the PowerShell.config.json (must be elevated to set -Scope Machine)
.EXAMPLE
Set-PowerShellConfig -PSModulePath (Convert-Path $Env:LOCALAPPDATA\PowerShell\Modules)
Change the Documents\PowerShell\Modules entry in your PSModulePath to be AppData\Local\PowerShell\Modules instead. Note this only changes the PSModulePath that PowerShell calculates, not your environment variables, nor anything your Profile adds.
#>
[CmdletBinding()]
param(
# Which config file to set
[ValidateSet("User","Machine","CurrentUser","LocalMachine")]
$Scope = "User",
[Parameter(Position=0, ValueFromPipeline)]
[hashtable]$InputObject = @{},
[ValidateScript({if (!(Test-Path -PathType Container $_)) {
throw "PSModulePath must be a folder!"
} $true })]
[string]$PSModulePath
)
# Strip common parameters if they're on here, so we can pass through everything else
$CommonParameters = @("Scope", "InputObject") +
[System.Management.Automation.Cmdlet]::CommonParameters +
[System.Management.Automation.Cmdlet]::OptionalCommonParameters
foreach ($name in @($PSBoundParameters.Keys.Where{ $_ -in $CommonParameters })) {
$null = $PSBoundParameters.Remove($name)
}
$Config = Get-PowerShellConfig $Scope -Iv Path
| Update-Object $InputObject
| Update-Object $PSBoundParameters
if ($DebugPreference -eq "Continue") {
Write-Debug "Set '$Path' content to:`n$($Config | ConvertTo-Json)"
}
$Config | ConvertTo-Json | Set-Content $Path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment