powershelloop

How to call a method inside another method in Powershell?


In my Powershell code bellow, inside the class XMLpipe the method get_processObj calls the method getObj_fromXML, but it returns the following error:

+         $this = getObj_fromXML
+                 ~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (getObj_fromXML:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

If I understood right, it is not calling the method correctly, so what would be the right way to call a method inside another method in Powershell class?

class XMLpipe 
{
    hidden $pp_path = (Join-Path $ENV:temp 'HPCMpipe.xml')
    hidden [System.Diagnostics.Process]$logoff_processObj
    hidden [String]$LastUpdate_SheetRange
    hidden [String]$reservationId

    XMLpipe()
    {
        if([System.IO.File]::Exists($this.pp_path))
        {
            $this = Import-Clixml -Path $this.pp_path
        }
    }

    [XMLpipe]getObj_fromXML()
    {
        $this = Import-Clixml -Path $this.pp_path
        return $this
    }

    [void]setObj_toXML()
    {
        $this | Export-Clixml -Path $this.pp_path
    }

    [void]set_processObj($value)
    {
        $this.logoff_processObj = $value
        setObj_toXML()  
    }

    [System.Object]get_processObj()
    {
        $this = getObj_fromXML
        return $this.logoff_processObj
    }

    [void]set_LastUpdate_SheetRange($value)
    {
        $this.LastUpdate_SheetRange = $value
        setObj_toXML($this)  
    }

    [string]get_LastUpdate_SheetRange()
    {
        $this = getpublic_pipeline
        return $this.LastUpdate_SheetRange
    }
}

#PROCESS 1:
$myobj = New-Object -TypeName XMLpipe

#This starts a 2nd process
$ProcessObj = Start-Process notepad -PassThru

$myobj.set_processObj($ProcessObj)

#PROCESS 3:
$myobj = New-Object -TypeName XMLpipe

#This gets the process object started in the 1st process
$ProcessObj = $myobj.get_processObj()

#This stops the 2nd process
$ProcessObj | Stop-Process 

Solution

  • All properties and methods when referenced inside a class in PowerShell should be referenced with the $this variable. That includes the logoff_processObj I believe you intended to assign here.

    [System.Object]get_processObj()
    {
        $this.logoff_processObj = $this.getObj_fromXML
        return $this.logoff_processObj
    }
    

    You are just referencing $this in a couple of methods. Please check this is what you intend to do, as you are then dealing with the entire instantiated object, not any of it's specific properties.