Search code examples
powershellpester

Mock with ParameterFilter Not Being Called (Pester)


enter image description here

I have a string array, $ServerNames, with two elements: 'ServerName1' and 'ServerName2'. I then have a corresponding MOCK:

Mock 'Get-ADComputer' { $Server1; write-host 'test'}    
Mock 'Get-ADComputer' { $foo } -ParameterFilter { $Identity -eq "$(${server_names}[0])" }

The mock without the filter gets called. The one that has the filter doesn't. If I remove the filter less mock, the Get-ADComputer commandlet is actually called. Why won't the filtered mock kick in?

F.Y.I., I tried $server_names[0] instead of interpolating them in a string.


Solution

  • So there are a couple things going on here.

    1. The Identity parameter is typed as Microsoft.ActiveDirectory.Management.ADComputer

    2. Comparisons in PowerShell attempt to convert objects that can't be directly compared. This is done from left to right.

    3. Comparisons between two ADComputer objects only check to see if they are literally the same object. Two objects that were created separately (even if with the same criteria) will not show as equal.

    The easy fix is to just reverse the comparison

    'ServerName' -eq $Identity
    

    That way $Identity is converted to a string, instead of the string being converted to an ADComputer object.