Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: use values from json as parameter defaults

I want to write a script with parameters, where the default values for those parameters are stored in a json file. Unfortunately, Powershell does not recognise param() if it is not the first line of code within the script.

But of course if it is the first line of the script, it cannot load the config in advance and use its value as default value. So I am in anpickle.

The config.json:

{"defaultValue":"Default"}

The powershell script:

$configPath = "config.json"
$configPath = Join-Path $PSScriptRoot $configPath

# read config
$config = Get-Content $configPath | ConvertFrom-Json

write-host $config.defaultValue

param($myparam = $config.defaultValue)

write-host $myparam

I am new to powershell, is there a way to set default values of parameters later in the script? Or alternatively, read parameters later into the script?

like image 763
Sandwichnick Avatar asked Apr 30 '26 09:04

Sandwichnick


1 Answers

Lets assume your config.json looks like this:

{
    "Name": "Earthling",
    "Color": "Pink"
}

Depending on your actual scenario you could pass the path to the config.json in as a parameter and make all the other parameters optional.

Within the script you load the config and provide default values for all parameters that have not been set in the script invocation:

[CmdletBinding()]
param (
    [Parameter()]
    [string]
    $Name,

    [Parameter()]
    [string]
    $Color,

    [Parameter()]
    [string]
    $ConfigPath
)

    if ($ConfigPath -in  $PSBoundParameters.Keys) {

        $config = Get-Content $ConfigPath | ConvertFrom-Json

        if ('Name' -notin  $PSBoundParameters.Keys) {
            $Name = $config.Name
        } 
        if ('Color' -notin  $PSBoundParameters.Keys) {
            $Color = $config.Color
        } 
    }

    Write-Host "$Name your favourite color is $Color"

You would call the script like this:

PS> ./script.ps1  -ConfigPath ./config.json -Color Blue

Earthling your favourite color is Blue

That has the downside, that you cannot declare parameters as mandatory. An alternative approach that allows declaring parameters as mandatory would be to pipe the configuration into your script:

[CmdletBinding()]
param (
    [Parameter(ValueFromPipelineByPropertyName,Mandatory)]
    [string]
    $Name,

    [Parameter(ValueFromPipelineByPropertyName,Mandatory)]
    [string]
    $Color
)

    Write-Host "$Name your favourite color is $Color"

The invocation would then be:

PS> Get-Content ./params.json | ConvertFrom-Json | ./script.ps1 -Color Red

Earthling your favourite color is Red
like image 177
Manuel Batsching Avatar answered May 02 '26 08:05

Manuel Batsching



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!