0

I have a json file and I need to add and update fields but facing field not found error. Details are mentioned below Please helperror image

Here is the sample of json

{
    "record":  [
                   {
                       "20230214":  {
                                        "out_time":  "02/14/2023 17:45:13",
                                        "total_active":  -2.3,
                                        "in_time":  "02/14/2023 17:48:13",
                                        "session":  [
                                                        {
                                                            "sout_time":  "02/14/2023 17:45:13",
                                                            "message":  "",
                                                            "active_time":  -2.3,
                                                            "sin_time":  "02/14/2023 17:48:13"
                                                        }
                                                    ]
                                    }
                   },
                   {
                       "20230215":  {
                                        "out_time":  "",
                                        "total_active":  0,
                                        "in_time":  "",
                                        "session":  [
                                                        {
                                                            "sout_time":  "02/14/2023 17:45:13",
                                                            "message":  "",
                                                            "active_time":  -2.3,
                                                            "sin_time":  "02/14/2023 17:48:13"
                                                        }
                                                    ]
                                    }
                   }
               ]
}

Here is the power shell code

$date = 20230216
$name = yanf
$compName = DEMOSERVER
$inTime = 02/16/2023 14:45:27
$outTime = 02/16/2023 13:40:09
<#
Set-UserStatus.ps1
****************************************************************
* ATTACH THIS SCRIPT TO USER LOGIN & LOGOUT  *
****************************************************************
#>

<#

    Logon – 4624 (Security event log)  -- 4634
    Logoff – 4647 (Security event log)
    Startup – 6005 (System event log)
    RDP Session Reconnect – 4778 (Security event log)
    RDP Session Disconnect – 4779 (Security event log)
    Locked – 4800 (Security event log)
    Unlocked – 4801 (Security event log)
    https://blog.netwrix.com/2016/01/15/how-to-get-user-logon-session-times-from-event-log/

#>

function Add-to-JSON{
    param (
        [String] $date,
        [String] $name,
        [String] $compName,
        [String] $inTime,
        [String] $outTime
    )

    Write-Output $date $name $compName $inTime $outTime

    #$jsonfile = "\\192.168.10.194\ADLogs\TimeTracker_log\"+$compName+"_"+$name+".json"
    $jsonfile = "E:\RK\Projects\Extras\tmp\"+$compName+"_"+$name+"_7.json"
    

    if (!(Test-Path -Path $jsonfile -PathType Leaf)){    # If file does not exists, create it
    
        $json = @{"record"= @()}             
        
    }
    else{
        $json = (Get-Content -Path $jsonfile | Out-String  | ConvertFrom-Json)   # Convert from JSON To Object  
        $hash = @{}
        $json.psobject.properties | Foreach { $hash[$_.Name] = $_.Value }
        $json = $hash
   
    }
    

    $time_diff = Get-Time-Diff $inTime $outTime

    $alreadyAddedFlag = $false

    
    
    if (($json.record.Length -eq 0) -or (-not $json.record.$date ) -or ($json.record.$date.Length -eq 0)){       # No Record exists for the date
        
        $new_session = @{ "sin_time"= $inTime; "sout_time"=$outTime; "message"=""; "active_time_minutes"=$time_diff }
        $today_dt =  @{"in_time"=$inTime; "out_time"=$outTime; "total_active_minutes"= $time_diff ; "session"= $new_session }
        $json.record += @{$date = $today_dt}     
        
       
    }
    else{
       if ($json.record.$date.out_time -eq $outTime){   # If record already exists
            $alreadyAddedFlag = $true       
       }
       else{           # New Session

           Write-Output $json.record $json.record.$date  
           <#
           $hash = @{}
           $json.record.$date.psobject.properties | Foreach { $hash[$_.Name] = $_.Value }
           $json.record.$date = $hash 
           #>
            
           $json.record.$date.total_active_minutes = $json.record.$date.total_active_minutes + $time_diff  # Add Total Time
           $json.record.$date.out_time = $outTime  
           $new_session = @{ "sin_time"= $inTime; "sout_time"=$outTime; "message"=""; "active_time_minutes"=$time_diff }    
           $json.record.$date.session += $new_session      
       }
    
    }

    
    Write-Output  $json.record $alreadyAddedFlag

    if (!$alreadyAddedFlag){

        $json | ConvertTo-Json -Depth 100 |  Out-File $jsonfile      # Convert back to JSON
    
     }    

}


function Get-Time-Diff{
    param (
        $startTime, 
        $endTime       
    )
    
    #Write-Output $startTime $endTime

    $diff= New-TimeSpan -Start $startTime -End $endTime
    
    #Write-Output "hi" $diff.Hours
    
    return $diff.TotalMinutes
     
}


# Get Entry Exit Time
function Get-EntryExitTime{
    #param (#[parameter(Mandatory=$false)] [boolean] $isEntry
        #[bool]$isLogin = $alse,
        #[bool]$isSignin = $false
        # [Parameter (Mandatory = $true)] [ValidateSet("Login","Unlock","Lock","Logout")]  [String]$process
    #)

    $username, $computername, $date =  Get-Details
    $startTime = ""
    $endTime = ""
    #$limitTimer = 6    

    # Check both Entry & Exit
    $time1 = Get-Time -ComputerName $computername -Username $username -process "Login"
    $time2 = Get-Time -ComputerName $computername -Username $username -process "Unlock"
    if ($time1 -ge $time2){
        $startTime =$time1
    }
    else{
        $startTime =$time2
    }
   
    #Write-Output $json.record.GetType()
       
    $time1 = Get-Time -ComputerName $computername -Username $username -process "Logout"
    $time2 = Get-Time -ComputerName $computername -Username $username -process "Lock"
    #$endTime = @({$time2},{$time1})[$time1 -gt $time2]  
    if ($time1 -ge $time2){
        $endTime =$time1
    }
    else{
        $endTime =$time2
    }     

    #Write-Output $time1 $time2 @startTime $endTime

    Add-to-JSON -date $date -name $username -compName $computername -inTime $startTime -outTime $endTime

    #return $startTime, $endTime
}





# Get "Login","Unlock","Lock","Logout" Time 
function Get-Time{
    param(  [Parameter (Mandatory = $true)] [String]$ComputerName,
            [Parameter (Mandatory = $true)] [String]$Username,
            [Parameter (Mandatory = $true)] [ValidateSet("Login","Unlock","Lock","Logout")]  [String]$process )

    $cmds = @{Login=4624; Unlock=4801; Lock=4800; Logout=4647}

    if ($process -eq "Login" ) {
         $cmd = Get-EventLog -LogName Security -ComputerName $ComputerName -InstanceId $cmds['Login'] -Message *$Username* -Newest 1
         return $cmd.TimeGenerated
    }
    elseif ($process -eq "Unlock" ) {
        $cmd = Get-EventLog -LogName Security -ComputerName $ComputerName -InstanceId $cmds['Unlock'] -Message *$Username* -Newest 1
        return $cmd.TimeGenerated
    }
    elseif ($process -eq "Lock" ) {
        $cmd = Get-EventLog -LogName Security -ComputerName $ComputerName -InstanceId $cmds['Lock'] -Message *$Username* -Newest 1
        return $cmd.TimeGenerated
    }
    elseif ($process -eq "Logout" ) {
        $cmd = Get-EventLog -LogName Security -ComputerName $ComputerName -InstanceId $cmds['Logout'] -Message *$Username* -Newest 1
        return $cmd.TimeGenerated
    }    
}


# Get Details
function Get-Details{
    $username = $((Get-WMIObject -class Win32_ComputerSystem).username -split "\\")[1]  #$env:USERNAME
    $computername = $env:COMPUTERNAME
    $date = (Get-Date).ToString('yyyyMMdd')

    return $username, $computername, $date
}



Get-EntryExitTime


R.K
  • 1,721
  • 17
  • 22
  • Please show us the exact arguments you're passing to `Add-to-Json` (particularly the `-date` parameter argumet) – Mathias R. Jessen Feb 16 '23 at 10:59
  • Your code sample as it stands isn't cut&pasteable so I can't test it here - for example you're got a function ```Get-Time-Diff``` which isn't defined, and if I bypass that I get a different error ```The property 'total_active_minutes' cannot be found on this object``` because your json property is called ```total_active``` - can you try running your code sample by cutting and pasting from this question and update it so it shows the error you're trying to resolve? You're more likely to get an answer if you make it reproducible for other people... – mclayton Feb 16 '23 at 11:18
  • Added the requested details above – R.K Feb 16 '23 at 11:55
  • [Member access enumeration](https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_member-access_enumeration) only works for reading. To write to the specific property you will need to address the specific property, e.g.: `$Json.Record[0].'20230214'.Session` or something like: `$Json.Record.Where{$_.PSObject.Properties.Name -eq '20230214'}.'20230214'.Session[0].message = 'Test'` – iRon Feb 16 '23 at 12:56
  • @iRon .. How to I append a new entry to $Json.Record.Where{$_.PSObject.Properties.Name -eq '20230214'}.'20230214'.Session ? – R.K Feb 16 '23 at 13:09
  • You might use the increase assignment operator (`+=`) for this: `$Json.Record.Where{$_.PSObject.Properties.Name -eq '20230214'}.'20230214'.Session += [pscustomobject]@{sout_time = "02/14/2023 17:45:13"; ... }` but be aware that the [`+=` operator is pretty expensive](https://stackoverflow.com/a/60708579/1701026) – iRon Feb 16 '23 at 15:15

0 Answers0