Powershell - 将 JSON 列和行写入 MSSQL DB
Powershell - Write JSON with column and row to MSSQL DB
我在 powershell 中有如下类型的 json 输出
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
内容如下
{
"columns": [
{
"name": "@timestamp",
"type": "datetime"
},
{
"name": "first.hostname",
"type": "text"
},
{
"name": "username",
"type": "text"
},
{
"name": "payload",
"type": "text"
},
{
"name": "domain",
"type": "text"
}
],
"rows": [
[
"2021-06-23T07:53:17.294Z",
"Name1",
"User1",
"Message",
"Domain"
],
[
"2021-06-23T07:53:17.294Z",
"Name1",
"User1",
"Message",
"Domain"
]
]
}
我需要能够将此列和行映射写入 MSSQL 数据库。我熟悉在 powershell 中将数据表写入数据库。我努力的部分是将此内容转换为适当的数据表。
创建一个 [DataTable]
,然后使用 columns
数组中的值定义列,并使用 rows
中的值填充 table:
# Convert JSON to a custom object
$tableDefinition = $json |ConvertFrom-Json
# Define type mappings
$typeMap = @{
datetime = [datetime]
text = [string]
}
# Create a datatable to hold the data
$dataTable = [System.Data.DataTable]::new()
# Create column definitions from JSON
foreach($column in $tableDefinition.columns){
[void]$dataTable.Columns.Add($column.name, $typeMap[$column.type])
}
# Populate table with rows
foreach($row in $tableDefinition.rows){
[void]$dataTable.Rows.Add($row)
}
我在 powershell 中有如下类型的 json 输出
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
内容如下
{
"columns": [
{
"name": "@timestamp",
"type": "datetime"
},
{
"name": "first.hostname",
"type": "text"
},
{
"name": "username",
"type": "text"
},
{
"name": "payload",
"type": "text"
},
{
"name": "domain",
"type": "text"
}
],
"rows": [
[
"2021-06-23T07:53:17.294Z",
"Name1",
"User1",
"Message",
"Domain"
],
[
"2021-06-23T07:53:17.294Z",
"Name1",
"User1",
"Message",
"Domain"
]
]
}
我需要能够将此列和行映射写入 MSSQL 数据库。我熟悉在 powershell 中将数据表写入数据库。我努力的部分是将此内容转换为适当的数据表。
创建一个 [DataTable]
,然后使用 columns
数组中的值定义列,并使用 rows
中的值填充 table:
# Convert JSON to a custom object
$tableDefinition = $json |ConvertFrom-Json
# Define type mappings
$typeMap = @{
datetime = [datetime]
text = [string]
}
# Create a datatable to hold the data
$dataTable = [System.Data.DataTable]::new()
# Create column definitions from JSON
foreach($column in $tableDefinition.columns){
[void]$dataTable.Columns.Add($column.name, $typeMap[$column.type])
}
# Populate table with rows
foreach($row in $tableDefinition.rows){
[void]$dataTable.Rows.Add($row)
}