[英]PowerShell nested object reference
Should be simple, but my inexperience is showing.应该很简单,但我的经验不足。
Using the similar data, I need to create INSERT to SQL Server in PowerShell 5:使用类似的数据,我需要在 PowerShell 5 中创建 INSERT 到 SQL Server:
{
"Libraries": {
"Reported": "2018-09-01T12:00:16",
"Locations": {
"Branch": [
{
"ID": "100",
"Address": "1 Elm Street",
"City": "Anytown",
"State": "ST",
"ZIP": "23466",
"Phone": "999-123-6543",
"Fax": "999-123-8395",
"Admin": "Doe, Jane"
},
{
"ID": "101",
"Address": "4 Main Street",
"City": "Anytown",
"State": "ST",
"ZIP": "23456",
"Phone": "999-123-4567",
"Fax": "999-123-4568",
"Admin": "Mouse, Noni"
}
]
}
}
}
First, I want to get a list as follows:首先,我想得到一个列表如下:
Branch Admin Address Phone Fax
------ --------- -------------------------------- ------------ -------------
100 Doe, Jane 1 Elm Street, Anytown, ST 23466 999-123-6543 999-123-8395
101 Mouse, Noni 4 Main Street, Anytown, ST 23456 999-123-4567 999-123-4568
I should do this like so, but I cannot find the way for a proper delve into the object structure:我应该这样做,但我找不到正确深入研究对象结构的方法:
Get-Content -Path c:\reports\libraries.json -raw | ConvertFrom-Json | ...
This will eventually feed Invoke-SQLCmd
for:这最终将为
Invoke-SQLCmd
提供:
Insert into Branch
(ID,Address,City,State,ZIP,Phone,Fax,Admin,Reviewed)
Values
(list from above)
The DB Reviewed
column will be Reported
from the JSON. DB
Reviewed
列将从 JSON Reported
。
Here's how to extract the branches as an array of [pscustomobject]
s from your JSON input, as well as the Reported
property value:以下是如何从 JSON 输入以及
Reported
属性值中提取分支作为[pscustomobject]
的数组:
# Read the JSON file into a hierarchy of custom objects.
$objsFromJson = Get-Content -Raw t.json | ConvertFrom-Json
# Use dot notation to access the property values of interest.
$branches = $objsFromJson.Libraries.Locations.Branch
$reported = $objsFromJson.Libraries.Reported
To integrate them into a string containing an INSERT INTO
SQL statement:要将它们集成到包含
INSERT INTO
SQL 语句的字符串中:
# Construct the arguments to the VALUES clause.
# Note: Assumes that all values are *strings*.
# Note: Only a limited number of arguments, presumably up to 1000, are supported.
$valuesClauseArgs = $branches | ForEach-Object {
# Create a list of single-quoted property values enclosed in parentheses.
"('" + ($_.psobject.properties.Value -join "', '") + "', '$reported')"
}
# Synthesize and output the full SQL statement
@"
INSERT INTO Branch
(ID,Address,City,State,ZIP,Phone,Fax,Admin,Reviewed)
VALUES
$($valuesClauseArgs -join ",`n ");
"@
With your sample input, the above yields the following string:使用您的示例输入,上面会产生以下字符串:
INSERT INTO Branch
(ID,Address,City,State,ZIP,Phone,Fax,Admin,Reviewed)
VALUES
('100', '1 Elm Street', 'Anytown', 'ST', '23466', '999-123-6543', '999-123-8395', 'Doe, Jane', '09/01/2018 12:00:16'),
('101', '4 Main Street', 'Anytown', 'ST', '23456', '999-123-4567', '999-123-4568', 'Mouse, Noni', '09/01/2018 12:00:16');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.