Converting CSV to JSON (PowerShell)
This article has not been completed yet. However, it may already contain helpful Information and therefore it has been published at this stage
Import-Module .\CSV2Json.psm1
Get-Module -Name CSV2Json
Get-Command -Module CSV2Json
Convert-CSV2Json
Convert-CSV2JsonWithParam -inputFiles "C:\temp\query_data_16_02_2022.csv" -delimiter ","
Convert-CSV2JsonWithParam -inputFiles "C:\temp\query_data_16_02_2022.csv","query_data_10_02_2022_1.csv" -delimiter ","
The Module:
## Loading Module
# Import-Module .\CSV2Json.psm1 / Import-Module <Path>\CSV2Json.psm1
## Checking if Module has been loaded successfully
# Get-Module -All / Get-Module -Name CSV2Json
## Showing all available Commands
# Get-Command -Module CSV2Json
## Removing Module
# Remove-Module CSV2Json
#------------------------------------------------------------------------------------------------------------------------------------------------
## Script Path Function
function Get-CurrentSriptPath {
process {
Switch ($Host.name){
'Visual Studio Code Host' { split-path $psEditor.GetEditorContext().CurrentFile.Path }
'Windows PowerShell ISE Host' { Split-Path -Path $psISE.CurrentFile.FullPath }
'ConsoleHost' { $PSScriptRoot }
}
}
}
## Data Picker Function
function Get-FileNames($InitialDirectory)
{
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.MultiSelect = $true
$OpenFileDialog.filter = "CSV - Documents (*.csv)|*.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.Filenames
}
## CustomInputBox Function
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
## CSV2JSON Convert Function
function Convert-CSV2JsonWithParam {
param
(
[string[]] $inputFiles,
[string] $delimiter
)
foreach ($inputFile in $inputFiles){
Get-Content -path $inputFile | ConvertFrom-Csv -Delimiter $delimiter | ConvertTo-Json | Out-File ((($inputFile.Split("."))[0]) + ".json")
}
}
## CSV2JSON Convert Function
function Convert-CSV2Json {
$path = Get-CurrentSriptPath
$inputFiles = (Get-FileNames $path)
Add-Type -AssemblyName Microsoft.VisualBasic
$delimiter = [Microsoft.VisualBasic.Interaction]::InputBox('Enter a delimiter', 'Set Delimiter')
foreach ($inputFile in $inputFiles){
Get-Content -path $inputFile | ConvertFrom-Csv -Delimiter $delimiter | ConvertTo-Json | Out-File ((($inputFile.Split("."))[0]) + ".json")
}
}
# Examples
# Convert-CSV2Json
# Convert-CSV2JsonWithParam -inputFiles "C:\temp\query_data_16_02_2022.csv" -delimiter ","
# Convert-CSV2JsonWithParam -inputFiles "C:\temp\query_data_16_02_2022.csv","query_data_10_02_2022_1.csv" -delimiter ","