Converting VBScript's Hex Function


Windows PowerShell


Definition: Returns a string representing the hexadecimal value of a number.

Hex

How do you convert a decimal number to a hexadecimal value? Why, you use the .NET formatting methods, of course. (How else would you do it?) For example, these two commands assign the value 4517 to the variable $a, then use .NET formatting to return the hexadecimal equivalent of 4517:



$a = 4517
$a = "{0:X}" -f $a

The formatting command is interpreted like this: you specify the format type in brackets - {} - with the entire method (brackets and all) enclosed in double quote marks. The 0 is the index number of the item to be formatted (in this case 0, because we're dealing with a single string value). The X indicates that we want to format the value as a hexadecimal number.

The format method is then followed by the -f parameter and the value to be formatted ($a).

When you run this command and then echo back the value of $a you should get the following:



11A5


Return to the VBScript to Windows PowerShell home page

Show: