25

I'm looking for example of how I would solve the scenario below:

Imagine my printer has the following property for "Status"
0 -Offline
2 -Paper Tray Empty
4 -Toner Exhausted
8 -Paper Jam

When I query status it returns a value of 12. I can obviously see that this means the printer has the Toner Exhausted and a Paper Jam, but how would I work this out with Powershell?

Thanks

2 Answers 2

41

The boolean bitwise and operator in Powershell is -band.

Assume you define your values and descriptions in a hashtable, and have the value of 12 from the printer:

 $status = @{1 = "Offline" ; 2 = "Paper Tray Empty" ; 4 = "Toner Exhausted" ; 8 = "Paper Jam" }
 $value = 12

Then, this statement will give you the textual descriptions:

$status.Keys | where { $_ -band $value } | foreach { $status.Get_Item($_) }

You could define the enum in Powershell, but the above works just as well, and defining enums in Powershell seems like a lot of work.

Here is an article, that talks about how to use the bitwise operators in Powershell.

Sign up to request clarification or add additional context in comments.

3 Comments

The last article URL does not exist anymore
Thanks, found another one to link to (the fallacies of 8-year old answers...)
10 years later, I'm just finally coming into interest in this bitwise stuff and found this answer incredibly helpful. Belated thanks!
11

You can let PowerShell do more of the work for you. Here's an example using System.IO.FileOptions:

PS> [enum]::GetValues([io.fileoptions]) | ?{$_.value__ -band 0x90000000}
RandomAccess
WriteThrough

2 Comments

Thanks Keith, do you happen to know if it's possible to enumerate the values of the UserAccountControl attribute for a user in AD?
If the attribute is a .NET attribute then yes. You just need to specify the full typename to [enun]::GetValues().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.