Home Dashboard Directory Help

$MyInvocation.MyCommand returns $Null when used as a param default with [CmdletBinding()] in ISE by sgrinker



Sign in
to vote
Type: Bug
ID: 797787
Opened: 8/19/2013 2:22:12 PM
Access Restriction: Public
User(s) can reproduce this bug


When using $Script:MyInvocation.MyCommand.Path (or $MyInvocation.MyCommand.Path) as a param default to return the current script path will return $Null when using with [CmdletBinding()] in ISE. This used to work in PowerShell v2, but appears to have started in PowerShell v3 and still exists in v4. The script will still function when executed from the CLI, but fails if executed directly in ISE. This does work when using the same default param value without [CmdletBinding()]. Also does not appear to be fixed by the following patch: http://support.microsoft.com/kb/2830615/en-us

Sign in to post a comment.
Posted by sgrinker on 8/29/2013 at 8:54 AM
I should clarify here that the $Null value only appears to be returned when the script is loaded in ISE and executed via F5/Run. Calling the saved script from the CLI works as expected.
Posted by sgrinker on 8/21/2013 at 1:15 PM
An alternative being to just reference the variable(s) later in the script if doing something simple in the example originally given. The problem is actually when you are trying to set the default of a parameter to something like the script path + subfolder + filename with datestamp. If using [CmdletBinding()] at the top of your script, this then requires you to check for $Null and update the variables at a $Script scope level. It works, but the design leaves something to be desired.
Posted by sgrinker on 8/21/2013 at 9:33 AM
Some further testing has shown the same to occur with $PSCommandPath and $PSScriptRoot. They both return null when set as the default value for a parameter when [CmdletBinding()] is used in the script. Without [CmdletBinding()] both work as expected. This is of course using a saved script.

The following will fail on Split-Path (or would just return $Null values):
     $CurrentPath = (Split-Path ($PSCommandPath)),
     $CurrentPath2 = $PSScriptRoot

Write-Host $CurrentPath
Write-Host $CurrentPath2

Again, removing or commenting out [CmdletBinding()] the script works as expected.

Sign in to post a workaround.