Search code examples
powershell

Struggling to give default parameter value to a '.ps1' script via the $PSDefaultParameterValues dictionary


I have a .ps1 that has a -path parameter that I would like to give a default value, via the $PSDefaultParameterValues dictionary, I figured this would work the same way as cmdlets:

$PSDefaultParameterValues=@{
    "C:\Users\user1\Documents\PowerShell\Scripts\myScript.ps1:path" = "C:\temp\db.jsonc"
}

The code for myScript.ps1 being:

[CmdletBinding()]
param (
    [Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName,mandatory)]
    [string]$Path
)
"path ---> $path"

So when I type .\myScript.ps1 I get the "Supply values for the following parameters:" prompt but if I run .\myScript.ps1 -path c:\some\path the output is path ---> c:\some\path

I tried reworking the dictionary but still the script does not receive a value for the -path parameter:

$PSDefaultParameterValues=@{
    #"myScript.ps1:path" = "C:\temp\db.jsonc"  
    "myScript.:pfath" = "C:\temp\db.jsonc"     # this does not work either
    #"C:\Users\user1\Documents\PowerShell\Scripts\myScript.ps1:path"    = "C:\temp\db.jsonc"
}

Solution

  • The about_Parameters_Default_Values never state that a script path is supported. Either use a default value in your script parameter and remove the Mandatory decoration:

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [ValidateNotNullOrEmpty()]
        [string] $Path = "C:\temp\db.jsonc"
    )
    
    "path ---> $path"
    

    Or use a function instead:

    function Test-Function {
        [CmdletBinding()]
        param (
            [Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Mandatory)]
            [string]$Path
        )
    
        "path ---> $path"
    }
    
    $PSDefaultParameterValues['Test-Function:Path'] = 'C:\temp\db.jsonc'
    Test-Function