Alek Davis
Alek Davis

Reputation: 10752

How to check command-line parameter from a PowerShell module?

Is there a way to check if a command-line parameter was specified for a PowerShell script from a module (.psm1 file)? I do not need the value, just have to know if the parameter was specified. The $PSBoundParameters.ContainsKey method does not seem to work.

TestParam.psm1:

function Test-ScriptParameter {
    [CmdletBinding()]
    param ()
    # This does not work (always returns false):
    return $PSBoundParameters.ContainsKey('MyParam')
}

Export-ModuleMember -Function *

TestParam.ps1:

[CmdletBinding()]
param (
    $MyParam= "Default"
)

$path = Join-Path (Split-Path -Path $PSCommandPath -Parent) 'TestParam.psm1'
Import-Module $path -ErrorAction Stop -Force

Test-ScriptParameter

This must return false:

PS>.\TestParam.ps1

This must return true:

PS>.\TestParam.psq -MyParam ""

This must return true:

PS>.\TestParam.ps1 -MyParam "Runtime"

Upvotes: 1

Views: 1134

Answers (2)

Alex Sarafian
Alex Sarafian

Reputation: 674

It cannot be done like you are thinking about it. The PSBoundParameters variable is native to the cmdlet's execution and as such depends on the param block of the cmdlet's definition. So in your case, the Test-ScriptParameter is checking if it was invoked with the parameter MyParam but since it doesn't specify it, then it will be always false.

To achieve what I believe you want, you need to create a function that checks into a hash structure like the PSBoundParameters for a specific key. The key needs to be provided by name. But then a simple $PSBoundParameters.ContainsKey('MyParam') wherever you need it should suffice.

Upvotes: 1

Mark Wragg
Mark Wragg

Reputation: 23385

The problem with your code is that you are checking the $PSBoundParameters value of the Function itself, which has no parameters.

You could make the function work by sending the $PSBoundParameters variable from the script in to the function via a differently named parameter.

For example:

TestParam.psm1:

function Test-ScriptParameter ($BoundParameters) {
    return $BoundParameters.ContainsKey('MyParam')
}

Export-ModuleMember -Function *

TestParam.ps1:

[CmdletBinding()]
param (
    $MyParam = "Default"
)

$path = Join-Path (Split-Path -Path $PSCommandPath -Parent) 'TestParam.psm1'
Import-Module $path -ErrorAction Stop -Force


Test-ScriptParameter $PSBoundParameters

Upvotes: 1

Related Questions