I have a scenario where I have to split a csv in certain number of rows, and for each batch there should be json file generated through PowerShell Script.
Here is what I am doing as of now:
$csv = "C:\Desktop\report.csv"
[int]$totalRows = 0
$reader = New-Object IO.StreamReader $csv
while($reader.ReadLine() -ne $null) { $totalRows++ }
$reader.Dispose()
$totalRows
$startRow = 0
$counter = 1
while($startRow -lt $totalRows)
{
Import-CSV $csv | Select-Object @{expression = { "Append this value"+ $_.Name}; label = 'NewName'}, @{expression = {$_.Account}; label = 'AccountNumber'} | Select-Object -skip $startRow -first 2 | ConvertTo-Json | Add-Content -Path "C:\Desktop\r_$($counter).json"
$startRow += 2
$counter++
}
The only problem here is that I am not able to enclose the Account number values in square bracket []:
Actual : "AccountNumber": "123"
expected : "AccountNumber": ["123"]
Also I am not sure on how to put whole json in each file under a root element through this. Also not sure if this "ConvertTo-Json" is the way to go as csv data needs to be edited, Please help.
Here is a csv for reference-
Name,Account,Role
John,123,Second
Rocky,345,Third
Tony,234,First
Rocky,345,Second
Matt,999,Second
Bernard,888,Third
Matt,999,First
Jacob,789,Second
Angela,777,Second
Jacob,789,First
Expected Output
First File:
{
"details":
[
{
"NewName": "Append this valueJohn",
"AccountNumber": ["123","333"]
},
{
"NewName": "Append this valueRocky",
"AccountNumber": ["345"]
}
]
}
Second File:
{
"details":
[
{
"NewName": "Append this valueTony",
"AccountNumber": ["234"]
},
{
"NewName": "Append this valueRocky",
"AccountNumber": ["345"]
}
]
}
So on till 6th file:
{
"details":
[
{
"NewName": "Append this valueAngela",
"AccountNumber": ["777"]
},
{
"NewName": "Append this valueJacob",
"AccountNumber": ["789"]
}
]
}
Thanks