Last active
September 11, 2024 02:31
-
-
Save Jaykul/37f985146e275a51060d1c3e4c74b922 to your computer and use it in GitHub Desktop.
Functions for powershell.config.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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