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
It does nothing, because you said to do nothing.
[void]TestFunction()
void instructs to suppress any output object.Here is working example:
class Test
{
[System.Diagnostics.Process[]]TestFunction()
{
return Get-Process
}
}
and no need to store results in intermediate variable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With