Mangling Exchange GUIDs

I spent a good few hours today attempting to use the MailboxGUID returned from the WMI Exchange provider to search for the associated Active Directory account, using the msExchMailboxGuid attribute.

Here's two functions I came up with in the end. One to convert MailboxGUID to something that a search on msExchMailboxGuid will like:

sub exch_to_ad {
  my $guid = shift;
  $guid =~ s/[\{\}]+//g;
  my $string = '';
  my $count = 0;
  foreach my $part ( split /\-/, $guid ) {
    $count++;
    if ( $count >= 4 ) {
      $string .= "\\$_" for unpack "(A2)*", $part;
    }
    else {
      $string .= "\\$_" for reverse unpack "(A2)*", $part;
    }
  }
  return $string;
}

And another to take a msExchMailboxGuid field, which is a byte array, and convert it to a MailboxGUID.

sub ad_to_exch {
  my $guid = shift;
  my @vals = map { sprintf("%.2X", ord $_) } unpack "(a1)*", $guid;
  my $string = '{';
  $string .= join '', @vals[3,2,1,0], '-', @vals[5,4], '-', 
     @vals[7,6], '-', @vals[8,9], '-', @vals[10..$#vals], '}';
  return $string;
}

Hopefully this should save other people some time.

Leave a comment

About bingos

user-pic System administrator, part-time Perl hacker, full-time POE [poe.perl.org] evangelist. One day he will be made to pay for his crimes. He has some modules on CPAN [cpan.org]. They may or may not be useful