如何在PowerShell中将多个json对象添加到一个json对象

时间:2017-03-17 15:42:44

标签: json powershell

cls

#function to Execute a stored procedure
function ExecSproc
{
    param ($Conn, $Sproc, $Parameters=@{})

    $MethodName = "ExecSproc"
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandType = [System.Data.CommandType]::StoredProcedure
    $SqlCmd.Connection = $Conn
    $SqlCmd.CommandText = $Sproc
    foreach($p in $Parameters.Keys){
        [Void] $SqlCmd.Parameters.AddWithValue("@$p",$Parameters[$p])
    }
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd)
    $DataSet = New-Object System.Data.DataSet
    [Void] $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
    return $DataSet.Tables[0]
}

function ExecuteSqlQuery ($SQLQuery, $ConnectionString) 
{
    $Datatable = New-Object System.Data.DataTable

    $MethodName = "ExecuteSqlQuery"
    $Connection = New-Object System.Data.SQLClient.SQLConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()
    $Command = New-Object System.Data.SQLClient.SQLCommand
    $Command.Connection = $Connection
    $Command.CommandText = $SQLQuery
    $Reader = $Command.ExecuteReader()
    $Datatable.Load($Reader)
    $Connection.Close()

    return $Datatable
}           

function SFSCheck()
{
    $OptionalField1 = ""
    $OptionalField2 = ""
    $SecondaryEmail = ""
    $EvaluationGroupCode = ""
    $DefaultRubricId = ""
    $DefaultWalktoolId = ""
    $EvaluatedInSFS = $true
    $EmploymentStatus = ""
    $Cert = ""
    $PrimaryEvalutor_payrollID = ""
    $SecondaryEvaluator_payrollID = ""
    $Access = ""
    $GoogleEmail = ""

    $PrimaryEvalutor_payrollID = $ManagerEmployeeNumber
    $OptionalField1 = ($EffectiveDate -as [string]).Split(" ")[0]

    $SFS = ExecSproc -Conn $AcctProConnectionString -Sproc SchoologySFSeSchoolGet -Parameters @{JobClassCode=$JobClassCode;Location=$CheckLocation}
    if ([string]::IsNullOrEmpty($SFS))
    {
        Write-Host "No Standards for Success account needed for combination of Job Class Code and location."
    }
    else
    {
        if ($SFS[7] -eq "Y")
        {
            if ($SFS[9] -ne "N")
            {
                $Access = $SFS[9]
                $Cert = $true

                #Check the Action Code to determine the status field
                if ($ActionCode -eq "LEAV")
                {
                    $EmploymentStatus = "Inactive"
                }
                elseif ($ActionCode -eq "TERM")
                {
                    $EmploymentStatus = "Remove"
                }
                elseif($ActionCode -eq "HIRE")
                {
                    $EmploymentStatus = "Add"
                }
                else
                {
                    $EmploymentStatus = ""
                }

                if(-not([string]::IsNullOrEmpty($StateId)))
                {
                    $StateId = $StateId.Substring(4).Trim()
                }

                #$personAsJson = "{SIEN=`"$StateId`";Payroll_id=`"$EmployeeNumber`";Email=`"$EmployeeEmail`";FirstName=`"$FirstName`";LastName=`"$LastName`";Position=`"$LongDescription`";Optional_Field1=`"$OptionalField1`";Optional_Field2=`"$OptionalField2`";Location_id=`"$CheckLocation`";Primary_Evalutor_id=`"$PrimaryEvalutor_payrollID`";Secondary_Evaluator_ids=`"$SecondaryEvaluator_payrollID`";EvalGroup_id=`"$EvaluationGroupCode`";Rubric_id=`"$DefaultRubricId`";Walk_id=`"$DefaultWalktoolId`";isEvaluated=`"$EvaluatedInSFS`";Employment_Status=`"$EmploymentStatus`";isCertified=`"$Cert`";Access=`"$Access`";Google_Email=`"$GoogleEmail`"}" 
                $User = New-Object Users
                $User.SIEN = $StateId
                $User.Payroll_id = $EmployeeNumber
                $User.Email = $EmployeeEmail
                $User.FirstName = $FirstName
                $User.LastName = $LastName
                $User.Position = $LongDescription
                $User.Optional_Field1 = $OptionalField1
                $User.Optional_Field2 = $OptionalField2
                $User.Location_id = $CheckLocation
                $User.Primary_Evaluator_id = $PrimaryEvalutor_payrollID
                $User.Secondary_Evaluator_ids = $SecondaryEvaluator_payrollID
                $User.EvalGroup_id = $EvaluationGroupCode
                $User.Rubric_id = $DefaultRubricId
                $User.Walk_id = $DefaultWalktoolId
                $User.is_Evaluated = $EvaluatedInSFS
                $User.Employment_Status = $EmploymentStatus
                $User.isCertified = $Cert
                $User.Access = $Access
                $User.Google_Email = $GoogleEmail

                $json.Add($User)
                #$response = Invoke-RestMethod 'http://example.com/api/SFS' -Method Put -Body $json

                #Write-Host "Adding $FirstName $LastName to Standards for Success file" -ForegroundColor Green
            }
        }
        else
        {
            Write-Host "Account does not need Standards for Success." -ForegroundColor Red
        }       
    }
}

$source = @"
public class Users
{
    public string SIEN;
    public string Payroll_id;
    public string Email;
    public string FirstName;
    public string LastName;
    public string Position;
    public string Optional_Field1;
    public string Optional_Field2;
    public string Location_id;
    public string Primary_Evaluator_id;
    public string Secondary_Evaluator_ids;
    public string EvalGroup_id;
    public string Rubric_id;
    public string Walk_id;
    public bool is_Evaluated;
    public string Employment_Status;
    public bool isCertified;
    public string Access;
    public string Google_Email;
}
"@

Add-Type -TypeDefinition $source

$AcctProConnectionString = "Server='167.217.10.172';Database='AccountProvision';trusted_connection=true;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $AcctProConnectionString

$Query = "SELECT TOP 3 * FROM FacultyAduit WHERE CaptureDateTime = '2017-03-16 10:00:00.000' ORDER BY CaptureDateTime DESC"
$AuditData = New-Object System.Data.DataTable
$AuditData = ExecuteSqlQuery -SQLQuery $Query -ConnectionString $AcctProConnectionString
$json = New-Object System.Collections.Generic.List[System.Object]

foreach($row in $AuditData)
{
    $EmployeeNumber = ""
    $FirstName = ""
    $LastName = ""
    $EffectiveDate = ""
    $JobClassCode = ""
    $LongDescription = ""
    $StateId = ""
    $CheckLocation = ""
    $ManagerEmployeeNumber = ""
    $ActionCode = ""
    $EmployeeEmail = ""

    $EmployeeNumber = $Row[2]
    $FirstName = $row[3].ToLower()
    $LastName = $Row[4].Replace(" ", "").Replace("-","").Replace("'","").ToLower()
    $EffectiveDate = $row[7]
    $JobClassCode = $row[16]
    $LongDescription = $Row[18].ToLower()
    $StateId = $Row[28]
    $CheckLocation = $Row[29]
    $ManagerEmployeeNumber = $row[33]
    $ActionCode = $Row[36]
    $EmployeeEmail = $Row[37].ToLower()

    SFSCheck
    Write-Host ""
}

$json | ConvertTo-Json

我有一个生成json用户对象的脚本,如下所示:

{
"SIEN" : "",
"Payroll_id" : "",
"Email" : "102_teacher@sandbox.com",
"FirstName" : "102_TEACHER",
"LastName" : "SANDBOX",
"Position" : "",
"Optional_Field1" : "",
"Optional_Field2" : "",
"Location_id" : "B102",
"EvalGroup_id" : "2182",
"Rubric_id" : "2344",
"Walk_id" : "",
"Employment_Status" : "active",
"isCertified" : true,
"Google_Email" : ""
}

但是我想生成一个json对象,其中包含我生成的所有用户对象,如下所示:

{
"Users":
[
    {
        "SIEN":  "",
        "Payroll_id":  "1203",
        "Email":  "hilds@myips.org",
        "FirstName":  "shannon",
        "LastName":  "hild",
        "Position":  "media assistant",
        "Optional_Field1":  "01/09/1989",
        "Optional_Field2":  "",
        "Location_id":  "B094",
        "Primary_Evalutor_id":  "12269",
        "Secondary_Evaluator_ids":  "",
        "EvalGroup_id":  "",
        "Rubric_id":  "",
        "Walk_id":  "",
        "isEvaluated":  "True",
        "Employment_Status":  "Inactive",
        "isCertified":  "True",
        "Access":  "Staff - Certified",
        "Google_Email":  ""
    },
    {
        "SIEN":  "10804749",
        "Payroll_id":  "8895",
        "Email":  "chizerc@myips.org",
        "FirstName":  "cynthia",
        "LastName":  "chizer",
        "Position":  "special education tchr",
        "Optional_Field1":  "08/25/1999",
        "Optional_Field2":  "",
        "Location_id":  "B105",
        "Primary_Evalutor_id":  "558",
        "Secondary_Evaluator_ids":  "",
        "EvalGroup_id":  "",
        "Rubric_id":  "",
        "Walk_id":  "",
        "isEvaluated":  "True",
        "Employment_Status":  "Inactive",
        "isCertified":  "True",
        "Access":  "Staff - Certified",
        "Google_Email":  ""
    }
]
}

我将这个json对象发送给API,但不确定如何将用户附加到一个对象。我已经尝试创建一个字符串并将所有内容添加到一个字符串并将该字符串转换为json对象,但这也不起作用。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您可以通过创建数组列表,使用PSCustomObject将用户从JSON转换为ConvertFrom-Json,将用户添加到列表中并使用{{1将列表转换回JSON }}

ConvertTo-Json

这会产生以下输出

$users = [System.Collections.ArrayList]::new();

$userAsJson = '
{
    "SIEN" : "",
    "Payroll_id" : "",
    "Email" : "102_teacher@sandbox.com",
    "FirstName" : "102_TEACHER",
    "LastName" : "SANDBOX",
    "Position" : "",
    "Optional_Field1" : "",
    "Optional_Field2" : "",
    "Location_id" : "B102",
    "EvalGroup_id" : "2182",
    "Rubric_id" : "2344",
    "Walk_id" : "",
    "Employment_Status" : "active",
    "isCertified" : true,
    "Google_Email" : ""
}';
$user = $userAsJson | ConvertFrom-Json;
$null = $users.Add($user);
$null = $users.Add($user);

$result = @{ Users = $users};

$result | ConvertTo-Json;