Pergunta

In PHP, there are "magic methods" that exist if you need them to. An example of this is the __toString() method which is used to echo out a specific string if a piece of code attempts to echo the object. This is an example using PHP:

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function __toString()
    {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

Which would return:

Hello

Is there a "magic function" that will do this in Powershell?

Foi útil?

Solução

All default PSObjects in PowerShell have a ToString() method, and if you're creating your custom objects in script (and not code), then you are going to have this method already present. All you need to to is override the ToString() method using Add-Member.

Please see this question for an exact description of this.

You can see what members your custom object has by piping an instance of the object to Get-Member.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top