Norrin Rad
Norrin Rad

Reputation: 991

Powershell calculation not returning value

Hi I'm trying to do a foreach loop to work through a csv file, nothing overly complex (or so i thought), however I'm not able to get the correct values back.

When I input the csv with the values below (which are in MB), I'd like to convert to gb, showing the comma for gb's.

CSV

DB1 10
DB2 1200
db3 50
db4 900

The values i get are

DB1 0
DB2 1
db3 0
db4 0

The script I have is

Import-Csv "c:\temp\sql.csv" | ForEach-Object {
    $db = $_.Name
    $size = $_.Size

    $newsize = $size/1000

    Write-Host "database $db is $newsize gb"  | Out-File "C:\temp\sql.txt" -Append
}

Thanks in advance

Upvotes: 0

Views: 118

Answers (1)

stackprotector
stackprotector

Reputation: 13608

You have a type problem. $size is of type int and therefore $size/1000 will be an integer division. You can cast the variable to double to force a floating point division:

Import-Csv "c:\temp\sql.csv" | ForEach-Object {
    $db = $_.Name
    $size = $_.Size

    $newsize = ([double]$size)/1KB

    "database $db is $([math]::Round($newsize,2)) GB" | Out-File "C:\temp\sql.txt" -Append
}

Upvotes: 2

Related Questions