Converting Numeric Strings

Converting a string that contains a number is trivial in PowerShell:

PS C:> [double]"77.234"

PS C:>

If the string contains a number format that is not a pure number, though, things become a challenge. If you receive a string like “2763MB” for example, PowerShell cannot automatically cast this to a number. Instead, you would need a converter function like this one:

function Convert-MBToByte($MBString)
    $number = $MBString.Substring(0, $MBString.Length-2)
    1MB * $number

Convert-MBToByte -MBString '2433MB'

Or, you could try and let PowerShell convert the input if it was in a valid PowerShell code format:

PS C:> Invoke-Expression -Command '2615MB'

PS C:>  

However, the use of Invoke-Expression is discouraged because it is considered a security risk for cases where a user would be able to adjust the expression that the command executes, similar to SQL-injection attacks.

Twitter This Tip! ReTweet this Tip!

GD Star Rating