I have written a PowerShell-script, which reads specific data-pieces out of a given JSON-file. Then reassembles the read data. Finally prepends the data to a existing CSV-file by adding it to the top of the file.
My script:
$srcFile = ".\output copy.json"
$targetFile = ".\demo1.csv"
# Exit the script, if one of the files is missing.
if (!(Test-Path $srcFile)) {
Write-Warning "${srcFile} is missing."
return
} elseif (!(Test-Path $targetFile)) {
Write-Warning "${targetFile} is missing."
return
}
# Read JSON-Report in.
$json = Get-Content -Path $srcFile | ConvertFrom-Json
# Fetch the relevant data from the nested JSON-structure.
$tests = $json.stats.tests
$passed = $json.stats.passes
$failures = $json.stats.failures
# Date-format (YYYY-MM-DDThh:mm:ss) not usable. Has to be converted.
$dateSegms = $json.stats.start.Split("T")[0].Split("-")
# Becomes: DD.MM.YYYY
$dateValid = $dateSegms[2] + "." + $dateSegms[1] + "." + $dateSegms[0]
$newEntry = "${tests};${passed};${failures};${dateValid}"
# Read the existing CSV-file in.
$existingCsv = Get-Content -Path $targetFile
# The entries have to be ordered descending.
$sUpdatedCsv = $newEntry + " " + $existingCsv
$aUpdatedCsv = $sUpdatedCsv.Split(" ")
# Remove the content of the CSV-file.
Clear-Content $targetFile
# Write the updated data to the CSV-file.
foreach ($line in $aUpdatedCsv) {
Add-Content -Path $targetFile "${line}"
}
# Delete the JSON-report.
Remove-Item -Path $srcFile
I'm not the most experienced PowerShell-programmer and would like to know where and how my code could be improved. Especially concerning my date-conversion.
Are there better ways in PowerShell to convert a date in the given format "YYYY-MM-DDThh:mm:ss" to the needed format "DD.MM.YYYY"?
The script produces the needed results. But are there flaws in my code?
All comments and answers concerning my approach welcomed.