Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Monday, June 24, 2013

Active Directory Module Filter/Hash compatibility issues Between V2 and V3

While assisting another IT Professional with a PowerShell issue, we came across a syntax difference between PowerShell V2 and V3 with regards to using a hash with the Get-ADUser cmdlet.  I was utilizing PowerShell V3 while the other individual was on V2.  Here is the code that worked on V3:
$ADHash = @{Filter = '(Surname -eq $Last) -and (GivenName -eq $First)';
SearchBase = $($OU.DistinguishedName)}           
Get-ADUser @ADHash
 
In this example, a hash is being created for the Get-ADuser cmdlet.  Both a value for the Filter and another for the SearchBase parameters were being created.  The problem came down to the filter.  In PowerShell V3, a complex filter is allowed.  That is, a filter that is using a logical operator such as –as or –or.  Here is the same code, but codded for V2.
Get-ADUser -filter * -SearchBase "$($OU.DistinguishedName)" |
Where-Object {($_.GivenName -eq $First) -and ($_.Surname -eq $Last)}
 
Utilizing any filtering capability that a cmdlet provides is much more efficient than piping objects to Where-Object.  In this case though, the Get-ADUser cmdlet provided with the ActiveDirectory Module on Windows Server 2008 R2 did not have this functionality.  Below is the error that the other IT Pro was receiving when he attempted to use the V3 code on a V2 domain controller.
Ge-AtDUser : The search filter cannot be recognized
At C:\BadgeUpdate1.ps1:18 char:11
+ Get-ADUser <<<<  @ADHash |
    + CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException
    + FullyQualifiedErrorId : The search filter cannot be recognized,Microsoft.ActiveDirectory.Management.Commands.Get
   ADUser

No comments: