I recently needed to test for parameter existence in a Powershell function. The idea was that if parameters were provided, the command should run directly in shell; else a GUI should be presented where the user can enter any of the parameters in a user-friendly way.
I started out with the "standard" test, using $args:
if ($args.Count -gt 0)
{
...
}
else
{
Show-GUI
}
Unfortunately, $Args turned out to always be zero (at least when using from within a module as in this case). I found help at this post at EggheadCafé though, switching $args for $MyInvocation.BoundParameters:
if ($MyInvocation.BoundParameters.Count -gt 0)
{
...
}
else
{
Show-GUI
}
A small word of warning though: $MyInvocation always refers to the "current context", which means that if you debug and try getting data, it will show the data for the current shell, not the function being debugged.
No comments:
Post a Comment