Author Posts

January 31, 2018 at 7:42 am

Hi,
I want to do something similar to this:

function foo
{
 write-host $($MyInvocation.MyCommand.Name)
}
foo

returns "foo"

how to achieve this with classes

class Foo
{
 static Bar()
 {
  write-host $("??")
 }
}
[Foo]::Bar()

I would it like to return both name of a class and a method if possible?

February 1, 2018 at 6:38 pm

Inside a class, I believe $this represents the current instance. You could pip that to Get-Member to derive its type name, for example. But it's not going to give you the currently-executing method; you should know that, because your code is *inside* that method already. .NET just doesn't visualize things that way.

February 1, 2018 at 11:02 pm

The call stack has the method name, and you can get the class name from the type. But you can't get the type dynamically from a static method because

$this

isn't populated.

class Test {
    [string] GetMyName() {
        return (Get-PSCallStack)[0].FunctionName + '.' + $this.GetType().Name
    }
}

[Test]::new().GetMyName()
# Test.GetMyName

Side note, if this was C# you could use

[System.Reflection.MethodInfo]::GetCurrentMethod()

, but in PowerShell that'll just give you the compiled LINQ expression of the currently running script block.

February 2, 2018 at 7:47 am

Exactly what I need, thank you.

edit:
ended up with something like this for my logging module:

function DoSomeLogging
{
    try
        {
             [void](Get-Variable this -ErrorAction Stop)
             $Static = $false
        }
        catch
        {
            $Static = $true
        }
        if ($Static)
        {
            return (Get-PSCallStack)[1].FunctionName
        }
        else
        {
            return $this.gettype().Name + '.' + (Get-PSCallStack)[1].FunctionName
        }
}

class Test
    {
    [string] GetMyName()
    {
        return DoSomeLogging
    }
    static [string] GetStaticName()
    {
        return DoSomeLogging
    }
}

[test]::new().GetMyName()
[test]::GetStaticName()