Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get-Process Does Not Work Within a Class [PowerShell]

I am trying to get running processes in a function within a class but it does nothing. Looks like the compiler ignores it, however, outside of the class it works perfectly.

<# Works here #>
#Get-Process

class Test
{
    [void]TestFunction()
    {
        <# DOES NOT WORK HERE #>
        Get-Process
    }
}

[Test]$object = [Test]::new()
$object.TestFunction()


<# Works here #>
#Get-Process

P.S. I am using PowerShell on macOS with VS Code

like image 243
Null Avatar asked Jan 25 '26 13:01

Null


2 Answers

It does nothing, because you said to do nothing.

[void]TestFunction()
  1. void instructs to suppress any output object.
  2. no return statement is defined within method.

Here is working example:

class Test
{
    [System.Diagnostics.Process[]]TestFunction()
    {
        return Get-Process
    }
}

and no need to store results in intermediate variable.

like image 166
Crypt32 Avatar answered Jan 27 '26 02:01

Crypt32


This happens, as classes work different a way from ordinary Powershell.

In class methods, no objects get sent to the pipeline except those mentioned in the return statement.

Thus, one needs a member variable that stores function result. Output can be then accessed via member, or, say, printed with write-host.

class Test
{
    $p =@()
    TestFunction()
    {
        $this.p=Get-Process # or get-process|write-host
    }
}

[Test]$object = [Test]::new()
$object.TestFunction()

$object.p
# Prints process list
like image 34
vonPryz Avatar answered Jan 27 '26 03:01

vonPryz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!