Windows PowerShell Home
$MyInvocation.MyCommand returns $Null when used as a param default with [CmdletBinding()] in ISE
8/19/2013 2:22:12 PM
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
How often does this happen?
Have you seen this problem before in this product?
I do not know if this issue existed previously
[string]$CurrentPath = (Split-Path ($Script:MyInvocation.MyCommand.Path))
[string]$CurrentPath = (Split-Path ($MyInvocation.MyCommand.Path))
This should return the current path of the running script if no value is passed for the parameter CurrentPath.
to post a comment.
Please enter a comment.
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.
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.
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
Again, removing or commenting out [CmdletBinding()] the script works as expected.
to post a workaround.
Please enter a workaround.
© 2013 Microsoft