$MyInvocation with classes

Welcome Forums General PowerShell Q&A $MyInvocation with classes

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
9 months, 2 weeks ago.

  • Author
    Posts
  • #92465

    Participant
    Points: 0
    Rank: Member

    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?

  • #92726

    Keymaster
    Points: 1,619
    Helping HandTeam Member
    Rank: Community Hero

    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.

  • #92749

    Participant
    Points: 35
    Rank: Member

    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.

    • #92768

      Participant
      Points: 0
      Rank: Member

      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()

The topic ‘$MyInvocation with classes’ is closed to new replies.