PowerShell嵌套对象参考

时间:2018-09-16 01:54:04

标签: json sql-server powershell object

应该很简单,但是我的经验不足。

使用类似的数据,我需要在PowerShell 5中创建对SQL Server的INSERT:

{
   "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"
            }
         ]
      }
   }
}   

首先,我想获得如下列表:

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

我应该这样做,但是我找不到适当的方法来研究对象结构:

Get-Content -Path c:\reports\libraries.json -raw | ConvertFrom-Json  | ...

这最终将为Invoke-SQLCmd提供以下内容:

Insert into Branch 
   (ID,Address,City,State,ZIP,Phone,Fax,Admin,Reviewed) 
Values
   (list from above)

DB Reviewed列将是JSON中的Reported

1 个答案:

答案 0 :(得分:1)

以下是从JSON输入中提取分支作为[pscustomobject]数组以及Reported属性值的方法:

# 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

要将它们集成到包含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  ");
"@

使用示例输入,以上代码将产生以下字符串:

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');