Classes in Powershell 5, need help creating $foo.bar.run() Classes in Powershell 5, need help creating $foo.bar.run() powershell powershell

Classes in Powershell 5, need help creating $foo.bar.run()


Define a new class for the Power functions and inject the IPAddress and Auth token into a new instance of that class in the constructor of the main class:

class VizioTVPower {    hidden [String]$IPAddress    hidden [String]$AuthToken    VizioTVPower([string]$IPAddress, [string]$AuthToken) {        $this.IPAddress = $IPAddress        $this.AuthToken = $AuthToken    }    [void]TurnOn() {        Set-Power -action "on" -IPAddress $this.IPAddress -auth $this.AuthToken    }    [void]TurnOff() {        Set-Power -action "off" -IPAddress $this.IPAddress -auth $this.AuthToken    }    [String]GetPowerStatus() {        Return Get-PowerStatus -IPAddress $this.IPAddress -auth $this.AuthToken    }}class VizioTV {    [String]$IPAddress    [String]$AuthToken    [VizioTVPower]$Power    VizioTV([string]$IPAddress, [string]$AuthToken) {        $this.IPAddress = $IPAddress        $this.AuthToken = $AuthToken        $this.Power = [VizioTVPower]::new($this.IPAddress, $this.AuthToken)    }}


You could create classes for Power and Input and store them as properties in your TV-class. Remember to pass a reference to the parent object (TV) so they can access the IPAddress and AuthToken-values.

class VizioTVInput {    [VizioTV]$TV    VizioTVInput([VizioTV]$TV) {        #Keep reference to parent        $this.TV = $TV    }    [string[]]List() {        return "Something"    }    [string]Current() {        return "Something"    }    [void]Set([string]$name) {        #Do something with $name    }}class VizioTVPower {    [VizioTV]$TV    VizioTVPower([VizioTV]$TV) {        #Keep reference to parent        $this.TV = $TV    }    [void]On() {        #Remove Write-Host, just used for demo        Write-Host Set-Power -action "on" -IPAddress $this.TV.IPAddress -auth $this.TV.AuthToken    }    [void]Off() {        Set-Power -action "off" -IPAddress $this.TV.IPAddress -auth $this.TV.AuthToken    }    [String]Status() {        return Get-PowerStatus -IPAddress $this.TV.IPAddress -auth $this.TV.AuthToken    }}Class VizioTV {    [String]$IPAddress    [String]$AuthToken    [VizioTVInput]$Input = [VizioTVInput]::new($this)    [VizioTVPower]$Power = [VizioTVPower]::new($this)    #Made it mandatory to input IP and AuthToken. Remove constructor if not needed    VizioTV([string]$IPAddress,[string]$AuthToken) {        $this.IPAddress = $IPAddress        $this.AuthToken = $AuthToken    }}$TV = New-Object VizioTV -ArgumentList "127.0.0.1", "AuthKey123"

Demo:

$TV.Power.On()#OutputsSet-Power -action on -IPAddress 127.0.0.1 -auth AuthKey123$TV.IPAddress = "10.0.0.1"$TV.Power.On()#OutputsSet-Power -action on -IPAddress 10.0.0.1 -auth AuthKey123