Author Posts

January 1, 2012 at 12:00 am

by yooakim at 2012-09-07 11:21:54

I've been fighting with this issue for a few hours know and I don't understand... hopefully someone here can enlighten my!

I am querying a non-Microsoft LDAP server. I get the data back and parts of the data are byte arrays.

I want to create a custom object so I have a ForEach loop in which I do:

$prop = $_.Properties

[PSCustomObject] @{
Path = $prop.adspath
CustomerId= [System.Text.Encoding]::UTF8.GetString($prop.damcustomerid)

The above code does not work, it just gives me:

Cannot convert argument "bytes", with value: "System.DirectoryServices.ResultPropertyValueCollection", for "GetString"
to type "System.Byte[]": "Cannot convert value "System.DirectoryServices.ResultPropertyValueCollection" to type "System
.Byte[]". Error: "Cannot convert the "System.Byte[]" value of type "System.Byte[]" to type "System.Byte".""

I've managed to fix this by adding | Select-Object as follows:

$prop = $_.Properties

[PSCustomObject] @{
Path = $prop.adspath
damcustomerid= [System.Text.Encoding]::UTF8.GetString(($prop.damcustomerid | select-object))

Now it works fine but since I don't understand what is going on I don't feel comfortable with the solution. Can anyone explain why I need to "select-object" to the the conversion of the array to a string to work?

by poshoholic at 2012-09-07 11:37:16

I think it's a matter of [System.Text.Encoding]::UTF8.GetString looking specifically for an array of bytes, and the System.DirectoryServices.ResultPropertyValueCollection does not implicitly convert into an array of bytes. You could probably have gotten it to work also by piping to ForEach {$_} instead of Select-Object, with the result being the same: PowerShell unwraps the collection, passes it down the pipeline, and then emits the objects which are gathered inside parentheses and converted back into a new collection (in your case a Byte Array). Note that in your solution if you happen to have only one byte you will get back a byte, not an array of bytes. To force it to be an array, use an array enclosure instead like this:
damcustomerid= [System.Text.Encoding]::UTF8.GetString(@($prop.damcustomerid | select-object))