PowerShell将随机数输出到CSV,CSV充满了空行

qq24tv8q  于 2023-11-14  发布在  Shell
关注(0)|答案(2)|浏览(116)

实际上这里有两个问题。下面的代码只输出1000个空行到CSV。我只是想输出一个随机范围的数字到CSV,我实际上需要跟进4列随机生成的数字,就像第一次尝试一样,所以第二部分是在解决第一个问题后,我如何将下一个范围定向到其他列?
第一个月

mcvgt66p

mcvgt66p1#

Export-CsvConvertTo-Csv相同,不是为了处理数组值而设计的:

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

字符串
这两个小工具都需要你为它们提供对象:

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


您可以使用PSCustomObject轻松创建新对象。
至于第二个问题,您可以通过调整以下代码动态创建数据集:

$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


很少有Csv输出行看起来像这样:

"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"
....

nqwrtyyt

nqwrtyyt2#

class rdot {[int]$num;[datetime]$dtg}
$dts=$(Get-Date).ToString("ddHHmmssMMMMyyyy").ToUpper()
$randoFile=".\$dts"+"_rando.csv"
while ($true){
$row=[rdot]::new()
$row.num=get-random -Maximum 26
$row.dtg=Get-Date
$row|Export-Csv -append $randoFile
Start-Sleep -S 1
}

字符串
然后可能看起来像这样?使用gc .\therandofile.csv -tail 137 -wait

13","10/19/2023 11:09:27 PM"
"1","10/19/2023 11:09:28 PM"
"3","10/19/2023 11:09:29 PM"
"11","10/19/2023 11:09:30 PM"
"24","10/19/2023 11:09:31 PM"
"22","10/19/2023 11:09:32 PM"
"13","10/19/2023 11:09:33 PM"
"7","10/19/2023 11:09:34 PM"
"2","10/19/2023 11:09:35 PM"
"13","10/19/2023 11:09:36 PM"
"18","10/19/2023 11:09:37 PM"
"3","10/19/2023 11:09:38 PM"
"15","10/19/2023 11:09:39 PM"
"16","10/19/2023 11:09:40 PM"
"19","10/19/2023 11:09:41 PM"
"23","10/19/2023 11:09:42 PM"
"14","10/19/2023 11:09:43 PM"
"1","10/19/2023 11:09:44 PM"
"19","10/19/2023 11:09:45 PM"
"25","10/19/2023 11:09:46 PM"
"6","10/19/2023 11:09:47 PM"
"4","10/19/2023 11:09:48 PM"
"22","10/19/2023 11:09:49 PM"
"20","10/19/2023 11:09:50 PM"

相关问题