Author Posts

May 16, 2015 at 2:17 pm

Hi all ,

I'm trying to build some class based DSC Resource using the latest release of PowerShell 5 April Preview .

I'm wondering how do you Debug methods inside the class ?? With functions I can specified parameters and see the output and set Breakpoints or "Write-Debug" .

So my question is how do I get inside the methods or how do I test those methods with different parameters .

[b]This is an example :[/b]

enum Ensure {

Absent
Present
}

[DscResource()]
class ClassService {

[DscProperty(Key)]
[string]$serviceName

[DscProperty(Mandatory)]
[Ensure] $Ensure

[DscProperty(Mandatory)]
[string] $Servicestatus

[ClassService] Get() {

$serviceExists = Get-Service -Name bits -ErrorAction SilentlyContinue

If ($ServiceExists.status -eq $this.ServiceStatus) {
Write-Verbose "Service status is correct"

}Else {
write-Verbose "Service status is not correct"

}
return $this

#$returnValue = @{
# ServiceName = [System.String]$this.ServiceName
# Servicestatus = [System.String]$serviceExists.Status
# Ensure = [System.String]$this.Ensure
#}
#return $returnValue

}

[void] Set() {

Write-verbose "Changing service status"

If ($this.serviceStatus -eq "Running") {
Start-Service -name $this.serviceName
}Else {
Stop-Service -name $this.ServiceName
}

}

[bool] Test() {
$serviceExists = Get-Service -Name $this.ServiceName -ErrorAction SilentlyContinue

if ($this.Ensure -eq 'Present') {
if($serviceExists -ne $null)
{
If ($serviceExists.status -eq $this.ServiceStatus) {
Write-Verbose "Nothing to configure – Service exists and has correct status"
Return $True
}Else {
Write-Verbose "Need to configure – Status is not correct"
Return $False
}
} else {
Write-Verbose "Nothing to configure – Service name does not exist"
return $false
}
} Else {
Write-Verbose "Nothing to configure – Ensure is Absent"
return $False
}

}

}

Regards

Mariusz

May 17, 2015 at 8:43 am

Hi Mariusz,

Just create an object instance of your class, set the member fields with test values and invoke the Get, Test and/or Set functions. You can set breakpoints as usual inside your class code.

$VerbosePreference = 'Continue'

# Instantiate an object of the class
$MyServiceObjcet = [ClassService]::new()

# Set member fields of the class
$MyServiceObjcet.Ensure = 'Present'
$MyServiceObjcet.serviceName = 'Browser'
$MyServiceObjcet.Servicestatus = 'Stopped'

# Invoke the functions
$MyServiceObjcet.Get()
$MyServiceObjcet.Test()

Regards
Daniel

May 17, 2015 at 10:34 am

HI Daniel ,

Thanks for help .

Regards

Mariusz