Use-CallerPreference

Sets the PowerShell preference variables in a module's function based on the callers preferences.

Syntax

Use-CallerPreference [-Cmdlet] <Object> [-SessionState] <SessionState> [<CommonParameters>]

Description

Script module functions do not automatically inherit their caller's variables, including preferences set by common parameters. This means if you call a script with switches like -Verbose or -WhatIf, those that parameter don't get passed into any function that belongs to a module.

When used in a module function, Use-CallerPreference will grab the value of these common parameters used by the function's caller:

This function should be used in a module's function to grab the caller's preference variables so the caller doesn't have to explicitly pass common parameters to the module function.

This function is adapted from the Get-CallerPreference function written by David Wyatt.

There is currently a bug in PowerShell that causes an error when ErrorAction is implicitly set to Ignore. If you use this function, you'll need to add explicit -ErrorAction $ErrorActionPreference to every function/cmdlet call in your function. Please vote up this issue so it can get fixed.

Related Commands

Parameters

Name Type Description Required? Pipeline Input Default Value
Cmdlet Object

[Management.Automation.PSScriptCmdlet] The module function's $PSCmdlet object. Requires the function be decorated with the [CmdletBinding()] attribute.

true false
SessionState SessionState

The module function's $ExecutionContext.SessionState object. Requires the function be decorated with the [CmdletBinding()] attribute.

Used to set variables in its callers' scope, even if that caller is in a different script module.

true false

EXAMPLE 1

Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

Demonstrates how to set the caller's common parameter preference variables in a module function.