Reputation: 27813
In my powershell module I have a function DoStuff
that takes parameter foo
. When you call the Initialize
function I want it to make all invocations of DoStuff
pass in a default value for foo
if not specified.
Normally, this is done via $PSDefaultParameterValues
however I have noticed functions run inside the modules and functions run outside the module (i.e. run from the shell) do not use the same default parameter dictionary.
An example is the following:
function Test1 ([Parameter(Mandatory=$true)][String]$testParam)
{
$global:PSDefaultParameterValues["Print:output"] = $testParam
}
function Test2 ([Parameter(Mandatory=$true)][String]$testParam)
{
$PSDefaultParameterValues["Print:output"] = $testParam
}
function CallPrint
{
Print
}
function Print([Parameter(Mandatory=$true)][String]$output)
{
Write-Host $output
}
To illustrate my issue I ran the following commands:
PS C:\Users\ms> Import-Module '.\Documents\Test Powershell Scripts\ModuleTest.psm1'
PS C:\Users\ms>Test1 abc
PS C:\Users\ms> Test2 def
PS C:\Users\ms> CallPrint
def
PS C:\Users\ms> Print
abc
What this shows is that $PSDefaultParameterValues
is used when calling a function from within the module, but $global:PSDefaultParameterValues
is used when calling a function from outside the module.
Is there any way to get consistent behavior without setting both of these at the same time?
Upvotes: 0
Views: 1471
Reputation: 68303
Since the Global scope and the module scope obviously have their on $PSDefaultParameterValues, you'll have to set both. You can simplify it by setting the global scope first, and then
$PSDefaultParameterValues = $Global:PSDefaultParameters.clone()
in the module to sync the values.
That being said, setting those values in the global scope sounds like a bad idea with a potential for unintended consequences.
Upvotes: 3