title: Convert GUID string to octetBytes using PowerShell
body: <p>I have a powershell script which outputs all Exchange 2003 mailboxes by size.</p>
  
  <pre><code>$computers = "vexch01","vexch02"
  foreach ($computer in $computers) {
    Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object -desc Size | select-object MailboxDisplayName,StoreName,@{Name="Size/Mb";Expression={[math]::round(($_.Size / 1024),2)}}, MailboxGUID | Export-Csv -notype -Path $computer.csv 
  }
  </code></pre>
  
  <p>Currently this outputs the MailboxGUID as a string type GUID (e.g. {21EC2020-3AEA-1069-A2DD-08002B30309D}).  I want to look up users in AD by this, but AD stores them in octetBytes format.</p>
  
  <p>I have found some <a href="http://www.leadfollowmove.com/archives/powershell/converting-a-guid-string-to-octet-string" rel="nofollow">powershell functions</a> which will do the conversion but only when the curly braces are removed.  The <a href="http://msdn.microsoft.com/en-us/library/560tzess.aspx" rel="nofollow">Guid.ToString</a> method should supply this, but I can't get it to work in the above.  </p>
  
  <p>However, if I could figure out how to do that, the <a href="http://msdn.microsoft.com/en-us/library/system.guid.tobytearray.aspx" rel="nofollow">Guid.ToByteArray</a> method might get me even closer.</p>
  
  <p>Has anyone cracked this?</p>
  
  <p>Update: the answers so far helped me write a function that converts the mailboxguid into the correct format for searching via LDAP.  However, I now cannot get this working in the script.  This is my updated script:</p>
  
  <pre><code>function ConvertGuidToLdapSearchString(
      [parameter(mandatory=$true, position=0)]$Guid
  )
  {
      $guid_object = [System.Guid]$Guid
      ($guid_object.ToByteArray() | foreach { '\' + $_.ToString('x2') }) -join ''
  }
  
  # Gets data through WMI from specified Exchange mailbox servers
  $servers = "vexch01","vexch02"
  foreach ($server in $servers) {
    Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object -desc Size | select-object MailboxDisplayName,StoreName,@{Name="Size/Mb";Expression={[math]::round(($_.Size / 1024),2)}}, @{Name="LDAP Guid";Expression={ConvertGuidToLdapSearchString(MailboxGUID)}} | Export-Csv -notype -Path $server.csv 
  }
  </code></pre>
  
  <p>I'm not sure why using the function in the <code>select-object</code> with <code>@{Name="LDAP Guid";Expression={ConvertGuidToLdapSearchString(MailboxGUID)}}</code> doesn't work.</p>
  
  <p>Is there another way of using this function in <code>select-object</code> that will give the string?</p>