Search code examples
powershellcsvrandom

PowerShell output random numbers to csv. CSV full of empty lines


Actually 2 part question here. The code below outputs nothing but 1000 blank lines to the csv. I'm just trying to output a random range of numbers to a csv and I actually need to follow up with 4 more columns of randomly generated numbers like this first attempt so the second part of this is after getting this first issue resolved how would I direct the next ranges to the other columns?

Get-Random -Count 998 -InputObject (8000..8999) | Export-Csv -Path SingleColumn.csv -NoTypeInformation


Solution

  • Export-Csv same as ConvertTo-Csv is not designed to deal with array of values:

    0..10 | ConvertTo-Csv # Outputs `AutomationNull.Value`
    

    Both cmdlets require you to feed them objects:

    0..10 | ForEach-Object { [pscustomobject]@{ foo = $_ } } | ConvertTo-Csv
    

    You can create new objects easily with PSCustomObject.

    As for the second question, you can dynamically create a dataset by tweaking this code:

    $columnsCount = 5
    $numberOfrows = 998
    $min = 8000; $max = 9000
    
    1..$numberOfrows | ForEach-Object {
        $out = [ordered]@{}
        foreach($column in 1..$columnsCount) {
            $out["Column $column"] = Get-Random -Minimum $min -Maximum $max
        }
        [pscustomobject] $out
    } | Export-Csv path/to/csv.csv -NoTypeInformation
    

    Few lines of Csv output would look something like this:

    "Column 1","Column 2","Column 3","Column 4","Column 5"
    "8314","8937","8789","8946","8267"
    "8902","8500","8107","8006","8287"
    "8655","8204","8552","8681","8863"
    "8643","8375","8891","8476","8475"
    "8338","8243","8175","8568","8917"
    "8747","8629","8054","8505","8351"
    "8102","8859","8564","8018","8817"
    "8810","8154","8845","8074","8436"
    "8626","8731","8070","8156","8459"
    ....