I'm working with a bitmask that represents error codes. For example, a value of 3 (binary 11) indicates that errors 1 and 2 were encountered (binary 1 and 10). I'm looking for a function that converts this to an array automatically in powershell.
I've looked around the internet and couldn't find anything particular to this scenario. I've written a function that does this, but it's not very readable if the user isn't familiar with bitmasks.
EDIT To be specific, I'm looking for a function that takes 'raw' error bits and uses that to return an array of errors. For example:
GetErrorList 3779
returns an array containing:
1, 2, 64, 128, 512, 1024, 2048
Set up a hashtable with translations for each bit and use the binary AND
operator (-band
) to find out what errors have been raised:
function Get-ErrorDescription {
param([int]$ErrorBits)
$ErrorTable = @{
0x01 = "Error1"
0x02 = "Error2"
0x04 = "Error3"
0x08 = "Error4"
0x10 = "Error5"
0x20 = "Error6"
}
foreach($ErrorCode in $ErrorTable.Keys | Sort-Object){
if($ErrorBits -band $ErrorCode){
$ErrorTable[$ErrorCode]
}
}
}
returns a string array of errors found, or $null
PS C:\> Get-ErrorDescription -ErrorBits 3
Error1
Error2
EDIT: I found a really cool way to do this with enum flags in Powershell 5:
[flags()] Enum ErrorTable
{
Error1 = 0x01
Error2 = 0x02
Error3 = 0x04
Error4 = 0x08
Error5 = 0x10
Error6 = 0x20
}
PS C:\> $errorcodes = [ErrorTable]'Error1,Error2'
PS C:\> $errorcodes
Error1, Error2
PS C:\> $errorcodes = [ErrorTable]3
PS C:\> $errorcodes
Error1, Error2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With