Is there any difference or drawback when always using $MyInvocation
or $PSBoundParameters
instead of $PSCmdlet.MyInvocation
or $PSCmdlet.MyInvocation.BoundParameters
respectively?
I already had a look at the following things:
Searched the internet (obviously)
about_automatic_variables
- There the following is written:
$MyInvocation is populated only for scripts, function, and script blocks.
- Furthermore, I know that the
$PSCmdlet
variable is only available when using [CmdletBinding()]
and a param ()
block.
- It looks like these variables were added quite some time ago (PowerShell v2.0?).
Then, I executed the following code within different contexts:
$PSCmdlet.MyInvocation.Equals($MyInvocation)
$PSCmdlet.MyInvocation.BoundParameters.Equals($PSBoundParameters)
These lines return true
in all the following cases (all files contain [CmdletBinding()]
and param ()
):
- Directly executed in a script
- When executed in a script via the call operator (
&
)
- When executed in a module cmdlet
So, is it recommended (and safe) to use $MyInvocation
and $PSBoundParameters
in every possible situation (i.e. script, function, module, etc.)? And do they always return the same values as the $PSCmdlet.*
counterparts (assuming that [CmdletBinding()]
is given)?
question from:
https://stackoverflow.com/questions/66060418/any-difference-or-drawback-of-using-myinvocation-instead-of-pscmdlet-myinvocat 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…