How to display an array of bytes in PowerShell as a joined string of hex digits?

5

I am using WMI to find out what my WWN (World Wide Name) is for my port on an HBA card. I can get the WWN back but it is contained as an 8 byte array. I would like to convert this byte array into a string of 16 hex digits for easy display.

This is the query I am using to print out each number in its own line. Is there a way to convert this to have the 8 lines combined onto a single line?

gwmi -namespace root\wmi -class MSFC_FibrePortNPIVAttributes | select -expand WWPN | foreach { $_.ToString("X2") }

I think the following can be used to test with just the byte data but I'm still new to PowerShell.

[byte[]] 1,2,3,4,5,6,7,8 | foreach { $_.ToString("X2") }

Jason

Posted 2010-08-26T18:30:56.173

Reputation: 280

Answers

5

Here are a few ways (I'm sure there are others):

[byte[]](1,2,3,4,5,6,7,8) | foreach { $string = $string + $_.ToString("X2") }
Write-Output $string

or

-join ([byte[]](1,2,3,4,5,6,7,8) |  foreach {$_.ToString("X2") } )

or

([byte[]](1,2,3,4,5,6,7,8) |  foreach { $_.ToString("X2") }) -join ""

Output for each of the above:

0102030405060708

Paused until further notice.

Posted 2010-08-26T18:30:56.173

Reputation: 86 075

This lead me down the correct path. I ended up with the following command that does what I need.

gwmi -namespace root\wmi -class MSFC_FibrePortNPIVAttributes | select WWPN | foreach {[array]::Reverse($_.WWPN); [BitConverter]::ToUInt64($_.WWPN, 0).ToString("X") }
 – Jason  – 2010-08-31T00:06:54.340

3

One way you could do it is like so:

[System.BitConverter]::ToString([Byte[]](1,2,3,4,5,6,7,8)) -replace "-"

Here's a breakdown:

[Byte[]](1,2,3,4,5,6,7,8)

This creates a ByteArray with 8 elements, each containing the value 1 through 8 respectively.

[System.BitConverter]::ToString(<ByteArray type Object>)

This converts the ByteArray to a dash-delimited string as so:

01-02-03-04-05-06-07-08

Lastly,

-replace "-"

This removes the dash.

Dave Sexton

Posted 2010-08-26T18:30:56.173

Reputation: 207

1Can you explain what this does? – Burgi – 2016-09-30T09:33:39.817

1While this may answer the question, it would be a better answer if you could provide some explanation why it does so. – DavidPostill – 2016-09-30T10:59:26.970