OSPowerShell.010: CSV Import and Export — Object Properties, Type Conversion and Validation

Rack of servers

Open-Source PowerShell Programming • Foundational • Estimated study time: 45 minutes.

A data center technician may need to save structured equipment readings for another shift or import a report for analysis. CSV represents tabular data as text, not a full copy of PowerShell’s object types. This lesson extends error handling and object output.

Learning objectives

Export objects with selected properties; import CSV rows; explain type loss; validate and convert integer readings; calculate aggregate power; use a private temporary workspace and clean up on exit.

Instructional demonstration of CSV import and export in PowerShell.

Objects and text

The Microsoft Export-Csv reference describes saving selected object properties as CSV. Import-Csv reconstructs rows as custom objects whose property values are strings. A string comparison may put 100 before 80 because it compares text; convert and validate numeric values before numerical sorting or filtering. Export the objects themselves rather than Format-Table output, which contains formatting instructions rather than the original records.

Rear of distributed filesystem servers at NERSC
Derrick Coetzee / Wikimedia Commons, CC0. Historical contextual photograph, not the example’s equipment.

Worked example: round-trip a small telemetry report

The example uses object pipelines and foreach loops. Run in PowerShell 7 in a disposable environment. It creates a unique directory in the system temporary location, writes synthetic data and deletes only that directory. Do not change the cleanup path to an arbitrary user-supplied value.

$ErrorActionPreference = 'Stop'
$dir = Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $dir | Out-Null
try {
    $file = Join-Path $dir 'readings.csv'
    $rows = @(
        [pscustomobject]@{ Rack = 'A'; Watts = 100 }
        [pscustomobject]@{ Rack = 'B'; Watts = 250 }
        [pscustomobject]@{ Rack = 'C'; Watts = 80 }
    )
    $rows | Export-Csv -LiteralPath $file -NoTypeInformation -Encoding utf8
    $loaded = @(Import-Csv -LiteralPath $file)
    $typed = foreach ($r in $loaded) {
        $n = 0
        if (-not [int]::TryParse($r.Watts, [ref]$n) -or $n -lt 0) {
            throw 'Invalid power reading'
        }
        [pscustomobject]@{ Rack = $r.Rack; Watts = $n }
    }
    $total = ($typed | Measure-Object -Property Watts -Sum).Sum
    $above = @($typed | Where-Object Watts -gt 100).Count
    if ($loaded.Count -ne 3 -or $total -ne 430 -or $above -ne 1) {
        throw 'Unexpected result'
    }
    "rows=$($loaded.Count) total=$total above100=$above"
} finally {
    Remove-Item -LiteralPath $dir -Recurse -Force
}

Expected output: rows=3 total=430 above100=1. The arithmetic is independently checked; the PowerShell executable was not available in the preparation environment, so the script itself was not executed.

Measurement interpretation

For simultaneous power readings the combined load is P = Σ Pi, where Pi is each rack’s measured power in watts. Here 100 + 250 + 80 = 430 W. For constant load over an interval t in hours, E = P × t Wh; a half-hour at 430 W would consume 215 Wh. Measurements taken at different times are not necessarily a simultaneous total.

Community discussion about Import-Csv returning strings; use the official documentation for behavior.

Safety, exercises and answers

Use synthetic input, verify headers and units, reject missing or malformed values, and avoid overwriting production reports. For CSV opened in spreadsheets, untrusted formula-like cells require additional protection. Exercise A: What is the imported type of Watts? B: Why validate before casting? C: Which rack exceeds 100 W? D: What is the total? E: Why use finally? Answers: A. String. B. Prevent invalid data becoming misleading measurements. C. B. D. 430 W. E. Ensure cleanup on handled exit paths.

Cover: Abigor / Wikimedia Commons, CC BY-SA 3.0; cropped to 1200 × 630, historical server photograph.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

BitcoinVersus.Tech donation QR code for 5,000 satoshis

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply