1

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.

Adam
  • 3,891
  • 3
  • 19
  • 42
  • It appears it cannot resolve the name. Is that server behind a different firewall? Have you tried explicitly typing the name in there and seeing if it works? – AussieJoe Apr 06 '18 at 21:29
  • AussieJoe, Thanks for the help! The "Get-ADComputer" call should never actually run (that's why I'm mocking it). The problem the "Get-ADComputer" call is getting picked up by the unfiltered mock and not the filtered one. I'm not sure why. – Adam Apr 06 '18 at 21:32
  • Have you inspected $ServerNames to ensure the names are actually correct? Isn't DistinguishedName for AD Users only? Can it be used for server objects too? My gut feeling is that $ServerNames is not what you think it is? – AussieJoe Apr 06 '18 at 21:38
  • Yea, there good. I return ADComputer objects in the mock. The objects are set like... $Server1 = New-Object 'Microsoft.ActiveDirectory.Management.ADComputer'; $Server1.DistinguishedName = 'Server1.test.local' – Adam Apr 06 '18 at 21:46
  • Can’t see the full code via your screenshot but is it correct your filter is referencing $server_names and not $servernames? – Mark Wragg Apr 06 '18 at 21:54
  • Oh order you declare the mocks in might be impacting your issue. Declare your filterless one last. – Mark Wragg Apr 06 '18 at 21:56
  • 2
    Although the wiki says filterless ones are always evaluated last. – Mark Wragg Apr 06 '18 at 21:59

1 Answers1

2

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.

Patrick Meinecke
  • 3,963
  • 2
  • 18
  • 26