Problem
You want to convert a number to a different base.
Solution
The PowerShell scripting language allows you to enter both decimal and hexadecimal numbers directly. It does not natively support other number bases, but its support for interaction with the .NET Framework enables conversion both to and from binary, octal, decimal, and hexadecimal.
To convert a hexadecimal number into its decimal representation, prefix the number by 0x to enter the number as hexadecimal: PS >$myErrorCode = 0xFE4A PS >$myErrorCode
65098 To convert a binary number into its decimal representation, supply a base of 2 to the [Convert]::ToInt32() method:
PS >[Convert]::ToInt32("10011010010", 2) 1234 To convert an octal number into its decimal representation, supply a base of 8 to the [Convert]::ToInt32() method:
PS >[Convert]::ToInt32("1234", 8) 668 To convert a number into its hexadecimal representation, use either the [Convert] class or PowerShell’s format operator:
PS >## Use the [Convert] class PS >[Convert]::ToString(1234, 16) 4d2
PS >## Use the formatting operator PS >"{0:X4}" f 1234 04D2
To convert a number into its binary representation, supply a base of 2 to the [Convert]::ToString() method:
PS >[Convert]::ToString(1234, 2) 10011010010 To convert a number into its octal representation, supply a base of 8 to the
[Convert]::ToString() method: PS >[Convert]::ToString(1234, 8) 2322
Discussion
It is most common to want to convert numbers between bases when you are dealing with numbers that represent binary combinations of data, such as the attributes of a file.
Simple Files in Windows PowerShell
When administering a system, you naturally spend a significant amount of time working with the files on that system. Many of the things you want to do with these files are simple: get their content, search them for a pattern, or replace text inside them.
For even these simple operations, PowerShell’s objectoriented flavor adds several unique and powerful twists.