Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

powershell - Any difference or drawback of using $MyInvocation instead of $PSCmdlet.MyInvocation

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...