Link to home
Start Free TrialLog in
Avatar of Chris Millard
Chris MillardFlag for United Kingdom of Great Britain and Northern Ireland

asked on

PowerShell - unexpected output when converting number

I have a PowerShell script that finds the last run result of a scheduled task. In this instance, the last run result is -2147024895

Now, in the PowerShell Window, if I enter the command:-

"0x{0:x}" -f -2147024895

The output shows:-

0x80070001

which is EXACTLY as I want.

Likewise, if I assign the value to a variable called lastResult as such:-

$lastResult = -2147024895

and then enter:-

"0x{0:x}" -f $lastResult

again I get an output of 0x80070001

HOWEVER, I cannot get the same output if I use a script! I have a .ps1 script that I want to run as a scheduled task that will send me an email with this last run result.

I have the following code ($lastResult is already set earlier on)

$lastResult = "0x{0:x}" -f $lastResult
$emailbody = "Last run result was " + $lastResult

When the email arrives, it reads:-

Last run result was 0x-2147024895

So I tried the line:-

$lastResult = [convert]::ToString($lastResult, 16)

which resulted in an email which read:-

Last run result was FFFFFFFF80070001

All I want is the 80070001 (preferably without using Trim)
Avatar of themrrobert
themrrobert
Flag of United States of America image

This should work for you:
$emailbody = "Last run result was " + ( "0x{0:x}" -f $lastResult )
Avatar of Chris Millard

ASKER

Sadly not. I still get:-

Last run result was 0x-2147024895
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Spot on  - thanks.
Hopefully you get it, my solution worked perfectly on my machine, so not sure why it wasn't working for you.

Good luck :)