Search code examples
powershelldsc

The results from running Test-TargetResource must be the boolean value True or False. DSC


i was trying to build a custom DSC resource, but it failed with the below error.

enter image description here

The returned results in a format that is not valid. The results from running Test-TargetResource must be the boolean value True or False.

When i run the function manually in a powershell prompt it does succeed and returns me a Boolean value.

enter image description here

Here's the code i used for Test-TargetResource

function Test-TargetResource
{

[OutputType([boolean])]
param (
[parameter(Mandatory)]
[string]
$vcentername,
[parameter(Mandatory)]
[string]
$credentialfile,
[parameter(Mandatory)]
[string]
$resourcepoolname,
[ValidateSet('Present','Absent')]
[string]
$Ensure = 'Present'
)

try 

{

#Addpssnapin VMware.VimAutomation.Core

$snap = Add-PSSnapin VMware.VimAutomation.Core

$MyCredentials= Import-Clixml $credentialfile

Write-Verbose "Connecting to vCenter $vcentername"

$connect = Connect-VIServer $vcentername -Credential $MyCredentials

Write-Verbose "Checking if the snapshots exist or doesnot exist"
$snapshotExist = (Get-ResourcePool $resourcepoolname | Get-VM | Get-Snapshot)


if ($Ensure -eq "Present") {

if ($snapshotExist) {

Write-Verbose "Snapshots Exists for these set of VM's. No need of taking further action"
return $true

} 
else {
Write-Verbose "Snapshots don't exists for these set of VM's in $resourcepoolname"
return $false
}
} 


else {

if ($snapshotExist) {
Write-Verbose "Snapshots exist on these VM's; snapshots must be removed."
return $false
} 

else {
Write-Verbose "Snapshots does not exist; nothing to remove."
return $true
}

}


}
    catch {
    $exception = $_
    Write-Verbose "Error occurred while executing Test-TargetResource function"
    while ($exception.InnerException -ne $null)
    {
    $exception = $exception.InnerException
    Write-Verbose $exception.message
    }
    }


    }

Can some one help me out.


Solution

  • Your catch block doesn't return a [bool]. You can see in the verbose output in your screenshot that the catch block is being hit. You should return $false at the end of the catch.

    catch {
        $exception = $_
        Write-Verbose "Error occurred while executing Test-TargetResource function"
        if ($exception.InnerException -ne $null)
        {
            $exception = $exception.InnerException
            Write-Verbose $exception.message
        }
        return $false
    }