1

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.

4
  • 2
    ${function:Show-Message}. Also $function: is not modifier. function: is a drive name. Nov 26, 2018 at 12:22
  • 1
    Calling ${function:Get-Member} is also not valid, as Get-Member is not a powershell function, but a cmdlet for compiled .net code from Microsoft.PowerShell.Commands.Utility.dll. Nov 26, 2018 at 12:34
  • @PetSerAl Thanks, this solves it... By the way, do you have a reference about what you just told me? I was assuming $function was something related to "scope" like $using and $global.
    – Thiago M
    Nov 26, 2018 at 12:39
  • I can not provide reference from memory. But you can easy check it. Apart from local, script, global, private, using and variable, IIRC, anything else interpreted as drive name. Nov 26, 2018 at 12:50

1 Answer 1

3

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}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.