Link to home
Start Free TrialLog in
Avatar of cyberleo2000
cyberleo2000Flag for United States of America

asked on

How can I convert a string to a number using powershell?

How can I convert this text string    4.296 MB (4,504,293 bytes)    to the number  4,504,293  ?


thank you
ASKER CERTIFIED SOLUTION
Avatar of footech
footech
Flag of United States of America 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
to the number  4,504,293
The footech solution will convert the string into a numeric value.  Do you want that conversion or should it remain a string with the embedded commas?

Here is a slightly different pattern that ignores everything after the numeric value, not just " bytes"
"4.296 MB (4,504,293 bytes)" -match "\(([0-9,]+) [^)]+\)$"
$matches[1]

Open in new window

Avatar of cyberleo2000

ASKER

I don't quite understand how it works, but it does, thank you
Basically it looks at your source string and tries to match it against a regular expression (regex).  When a match is found (the comparison using the -match operator evaluates to true), then the $Matches automatic variable is populated.  The regex includes a capturing group which is what is referenced by $Matches[1] ($Matches[0] includes the entire match), and [int] casts the string in $Matches[1] as an integer.