Search code examples
arrayspowershellsum

PowerShell Sum Array That Already Contains MBs


I have an array that contains MBs already in the values. This is how MS DPM returns data written to a tape. I would like to sum them together. Is there an easy one liner to accommodate for this?

enter image description here


Solution

  • MB is a recognized numeric suffix in PowerShell's native grammar, so you can parse and evaluate your size strings with Invoke-Expression:

    PS ~> Invoke-Expression '2401927.56MB'
    2517924115906.56
    

    You'll want to do some basic input validation to make sure it's actually a numeric sequence, and remove the thousand separator:

    $Tapes.DataWrittenDisplayString |ForEach-Object {
        # remove commas and whitespace
        $dataWritten = $_ -replace '[,\s]'
        # ensure it's actually a number in the expected format
        if($dataWritten -match '^\d+(?:\.\d+)?[kmgtp]b$'){
            # let PowerShell do the rest
            $dataWritten |Invoke-Expression
        }
    }