Andy White
Andy White

Reputation: 65

converting string to number in powershell

I am trying to convert a string to a 2 decimal place value

I have a script that has a line of code which is

(get-mailboxdatabase xxx -status).databasesize

This returns the size something like 1.008 GB (1,082,195,968 bytes)

I want to be able to convert this to a number (1.008) and can't work out how to do it.

I know about ToGB() but that only works when running the script from EMS.

I need to be able to run the script in Powershell and not EMS as the script does other things.

How do I convert the value to a number?

TIA

Andy

Upvotes: 2

Views: 3533

Answers (4)

Swoogan
Swoogan

Reputation: 5558

You can convert numbers to the various number types using standard .NET framework types and conversions. For example:

> $var = [decimal]::Parse("1.008")
> $var.GetType().Name
Decimal

Extracting just that portion of the string from the input is a separate issue, and it's hard to tell from your question which is giving you trouble. To get just the number, you might use something like this:

$input = (get-mailboxdatabase xxx -status).databasesize
$strSize = $input.Split(' ')[0]

Or you can use a regular expression. It all depends on how variable your size is.

Upvotes: 1

hdev
hdev

Reputation: 6537

This is very easy, just make a cast and divide with 1GB.

PS C:\> [int]"1082195968"/1GB
1,00787353515625

enter image description here

Or in your case

([int](get-mailboxdatabase xxx -status).databasesize)/1GB

Upvotes: 1

CB.
CB.

Reputation: 60976

try this:

$val= (get-mailboxdatabase xxx -status).databasesize
[decimal]([regex]::Match( $val, '(^.+)GB' )).groups[1].value

Upvotes: 0

mjolinor
mjolinor

Reputation: 68341

If you're using implicit remoting (it sounds like you are), that's going to be a [string], so you'll need to use string methods.

'1.008 GB (1,082,195,968 bytes)' -replace '^([0-9.]+).+','$1'
1.008

Upvotes: 1

Related Questions