Reputation: 191
I recently discovered that you can get powershell's functions by reference using the modifier $function:
. But I noticed a strange problem...
By convention, POSH uses a {Verb}-{Noun}
convention for function names, where {Verb}
is part of aproved POSH verb names. For instance: Get-Member
or Invoke-WebRequest
.
The thing is, that calling $function:Get-Member
, for example, is not valid because of the hyphen; it works just fine if you declare a function like ShowMessage
and calls: $fn = $function:ShowMessage
. So I'd like to know if there's a way to escape this call.
PS.: I do know of another option, but is much much more verbose:
function Show-Message { Write-Host "Foo"; }
$fn = (Get-Item "function:Show-Message").ScriptBlock;
$fn.Invoke();
Update: Although @PetSerAl was very helpfull and explained the problem, I'll mark @Ansgar Wiechers's response as the answer because it's better documented.
Upvotes: 1
Views: 2560
Reputation: 200293
function:
is a PSDrive, not a (scope)modifier. As for using it with variable-like notation ($function:name
): the rules for variable names with special characters apply here as well.
From the documentation:
VARIABLE NAMES THAT INCLUDE SPECIAL CHARACTERS
Variable names begin with a dollar sign. They can include alphanumeric characters and special characters. The length of the variable name is limited only by available memory.
Whenever possible, variable names should include only alphanumeric characters and the underscore character (_).Variable names that include spaces and other special characters, are difficult to use and should be avoided.
To create or display a variable name that includes spaces or special characters, enclose the variable name in braces. This directs PowerShell to interpret the characters in the variable name literally.
Your notation should thus look like this:
${function:Show-Message}
It can be invoked like this:
& ${function:Show-Message}
Upvotes: 3