clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy -WarningAction SilentlyContinue

$TestInputs=$args
$userName=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$testFreRpt=$TestInputs[2]
$inputUsrKey=$TestInputs[3]
$arrStrng=$TestInputs[4]
$proxyUsr=$TestInputs[5]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[6]

$odbOpertns=$arrStrng.ToString().Trim().Split('#')
$fileOpe=$odbOpertns[0].ToString().Trim().Split('~')
$folderOpe=$odbOpertns[1].ToString().Trim().Split('~')
$syncOpe=$odbOpertns[2].ToString().Trim().Split('~')
$sharngOpe=$odbOpertns[3].ToString().Trim().Split('~')
$siteAdminOpe=$odbOpertns[4].ToString().Trim().Split('~')

$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')

$tstArr=$testFreRpt.Split('#')
$testFrequency=[int]$tstArr[0]
$reportingNam=$tstArr[1]
$showUsrFileOpe=$tstArr[2]
$rptPath='ODB/'+$reportingNam

Function Start-SleepWithProgress {
	Param([int]$sleeptime)

	For ($i=0;$i -le $sleeptime;$i++){
		$timeleft = ($sleeptime - $i);
		Write-Progress -Activity "Sleeping" -CurrentOperation "$Timeleft More Seconds" -PercentComplete (($i/$sleeptime)*100);
		start-sleep 1
	}
	
	Write-Progress -Completed -Activity "Sleeping"
}

Function New-CleanSPOSession {
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)
    $i = 0
	while (($Credential -eq $Null) -and ($i -lt 5)){
		$script:Credential = Get-Credential -Message "Please provide your Exchange Online Credentials"
		$i++
	}

	if ($Credential -eq $null){
		Write-Error -Message "Failed to get credentials" -ErrorAction Stop
	}

	Get-PSSession | Remove-PSSession -Confirm:$false
	[System.GC]::Collect()
	Start-SleepWithProgress -SleepTime 15
	$Error.Clear()
	
    $sessionOption = New-PSSessionOption -SkipRevocationCheck
	if($proxyUsr.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
	    $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
	    $sessionOption = New-PSSessionOption -SkipRevocationCheck -ProxyAccessType WinHttpConfig -ProxyAuthentication Basic -ProxyCredential $proxyCred
	}
	$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $azureEnvArr[1] -Credential $Credential -Authentication Basic -AllowRedirection -SessionOption $sessionOption -WarningAction SilentlyContinue
		
	if ($Error.Count -gt 0){
		$ErrorCount++
		if ($ErrorCount -gt 3){
			exit
		}
		Start-SleepWithProgress -sleeptime 60
		New-CleanSPOSession
	}
	else {
		$ErrorCount = 0
	}
	$null = Import-PSSession $session -AllowClobber -WarningAction SilentlyContinue -DisableNameChecking
	Set-Variable -Scope script -Name SessionStartTime -Value (Get-Date)
}

$fileAct=@{}
foreach($act in $fileOpe){  
    $fileAct.Add($act,0)
}

$folderAct=@{}
foreach($act in $folderOpe){ 
    $folderAct.Add($act,0)
}

$syncAct=@{}
foreach($act in $syncOpe){  
    $syncAct.Add($act,0)
}

$sharngAct=@{}
foreach($act in $sharngOpe){  
    $sharngAct.Add($act,0)
}

$siteAdminAct=@{}
foreach($act in $siteAdminOpe){  
    $siteAdminAct.Add($act,0)
}

# hash for summary counts
$uniqOpe=@{}
$uniqusers= @{}
$uniqClientIp=@{}
$uniqsites=@{}
$uniqItem=@{}
$uniqDestnatn=@{}
$uniqUsrAgent=@{}

$uniqFdrOpe=@{}
$uniqFdrusers= @{}
$uniqFdrClientIp=@{}
$uniqFdrsites=@{}
$uniqFdrItem=@{}
$uniqFdrDestnatn=@{}
$uniqFdUsrAgent=@{}

$uniqSyncOpe=@{}
$uniqSyncUsers= @{}
$uniqSyncClientIp=@{}
$uniqSyncSites=@{}
$uniqSyncItem=@{}
$uniqSyncDestnatn=@{}
$uniqSyncUsrAgent=@{}

$uniqShrOpe=@{}
$uniqShrUsers= @{}
$uniqShrClientIp=@{}
$uniqShrSites=@{}
$uniqShrItem=@{}
$uniqShrDestnatn=@{}
$uniqShrUsrAgent=@{}

$uniqAdmnOpe=@{}
$uniqAdmnUsers= @{}
$uniqAdmnClientIp=@{}
$uniqAdmnSites=@{}
$uniqAdmnItem=@{}
$uniqAdmnDestnatn=@{}
$uniqAdmnUsrAgent=@{}

$usrFileOpe=@("FileAccessed","FileCheckedIn","FileCheckedOut","FileDeleted","FileUploaded")

$usrKeyArr=$inputUsrKey.Split(',')
$filePath=''
$kfilePath=''

$sysDat=(Get-Date).ToUniversalTime()
$endDat=$sysDat.AddMinutes(-60)
$startDat=$endDat.AddMinutes(-($testFrequency))

Try{
    Import-Module MsOnline
    Set-StrictMode -Version 2
    $ErrorCount = 0

    New-CleanSPOSession
    
    Try{
        $actWritArr = Eg-WriteFile -ComntRptPath $rptPath -FileName "odbActOprBase" -keyFileName "kodbActOprBase" -EgPath $egurkhaPath
        Search-UnifiedAuditLog -StartDate $startDat -EndDate $endDat | select AuditData,Operations |Export-Csv $actWritArr[1]
        $null=Protect-File  $actWritArr[1] -Algorithm AES -KeyAsPlainText $actWritArr[0] -RemoveSource
    }Catch{}

    $actReadArr=Eg-ReadFile -ComntRptPath $rptPath -FileName "odbActOprBase" -keyFileName "kodbActOprBase" -EgPath $egurkhaPath
    $unProtctAct=$actReadArr[1] -replace (".csv",".dat") 
    $actPath=Unprotect-File $unProtctAct -Algorithm AES -KeyAsPlainText $actReadArr[0]	
    $serchAuditLog= import-csv $actPath
    Remove-Item $actPath
 
    $filePath=$actReadArr[2]+''+$actReadArr[3]
    $kfilePath=$actReadArr[2]+''+$actReadArr[4]
    
    Get-PSSession | Remove-PSSession
}
Catch{
    Write-Host 'Exception Occured in SPO Activity operation "Search-UnifiedAuditLog" - ' $_.Exception.Message !>
}
Try{

    foreach($log in $serchAuditLog){

         #'if' condition for if userkey is in {NT AUTHORITY\SYSTEM,SHAREPOINT\system} or not
        if($inputUsrKey -ne "" -and $inputUsrKey -ne $null -and $inputUsrKey -ne "No" -and $inputUsrKey -ne "false"){
            $res= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $fileOpe -and $_.UserKey -notin $usrKeyArr}
            $resFldr= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $folderOpe -and $_.UserKey -notin $usrKeyArr}
            $resSync= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $syncOpe -and $_.UserKey -notin $usrKeyArr}
            $resShrg= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $sharngOpe -and $_.UserKey -notin $usrKeyArr}
            $resSAdm= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $siteAdminOpe -and $_.UserKey -notin $usrKeyArr}
        }else{
            $res= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $fileOpe}
            $resFldr= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $folderOpe }
            $resSync= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $syncOpe }
            $resShrg= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $sharngOpe }
            $resSAdm= $log.AuditData | ConvertFrom-Json | Where-Object {$_.Workload -eq "OneDrive" -and $_.Operation -in $siteAdminOpe }
        }

        # ******* FILE OPERATIONS ********* 

        if($res -ne "" -and $res -ne $null){ 
	    if($showUsrFileOpe -eq 'no'){
                if(($res.UserId -eq $userName) -and ($res.Operation -in $usrFileOpe )){
                    continue;
                }
            }
        
            $isUserAgent=[bool]($res.PSobject.Properties.name -match "UserAgent")
            $isSiteUrl=[bool]($res.PSobject.Properties.name -match "SiteUrl")  
	    if($isSiteUrl -eq $false -or $isUserAgent -eq $false){
                    continue;
            }  

            if($uniqOpe.ContainsKey($res.Operation)){
                $uniqOpe[$res.Operation]=[int]$uniqOpe[$res.Operation]+1
            }else{
                $uniqOpe.Add($res.Operation,1) 
            }

            $uniqUsrLine=$res.UserId+'#'+$res.ClientIP
            if($uniqusers.ContainsKey($uniqUsrLine)){          
                $output=[String]$uniqusers[$uniqUsrLine]
                $arr=$output.Split('#')
                if($output.Contains($res.Operation)){
                    $uniqusers[$uniqUsrLine]=$arr[0]+'#'+[String]([int]$arr[1]+1)
                }else{
                    $uniqusers[$uniqUsrLine]= $arr[0]+','+$res.Operation+'#'+[String]([int]$arr[1]+1)
                }               
            }else{
                $uniqusers.Add($uniqUsrLine,$res.Operation+'#'+1) 
            }

            if($uniqClientIp.ContainsKey($res.ClientIP)){
                $ipOutput=[String]$uniqClientIp[$res.ClientIP]
                $ipArr=$ipOutput.Split('#')
                if($ipOutput.Contains($res.Operation)){
                    $uniqClientIp[$res.ClientIP]=$ipArr[0]+'#'+[String]([int]$ipArr[1]+1)
                }else{
                    $uniqClientIp[$res.ClientIP]= $ipArr[0]+','+$res.Operation+'#'+[String]([int]$ipArr[1]+1)
                }               
            }else{
                $uniqClientIp.Add($res.ClientIP,$res.Operation+'#'+1)
            }        

            if($isSiteUrl){
                $uniqsiteLine=$res.SiteUrl+'#'+$res.Site
            }else{
                $uniqsiteLine='-#'+$res.Site
            }
            if($uniqsites.ContainsKey($uniqsiteLine)){
                $siteOutput=[String]$uniqsites[$uniqsiteLine]
                $siteArr=$siteOutput.Split('#')
                if($siteOutput.Contains($res.Operation)){
                    $uniqsites[$uniqsiteLine]=$siteArr[0]+'#'+[String]([int]$siteArr[1]+1)
                }else{
                    $uniqsites[$uniqsiteLine]= $siteArr[0]+','+$res.Operation+'#'+[String]([int]$siteArr[1]+1)
                } 
            }else{
                $uniqsites.Add($uniqsiteLine,$res.Operation+'#'+1)
            }

            if($uniqItem.ContainsKey($res.ItemType)){
                $itemOutput=[String]$uniqItem[$res.ItemType]
                $itemArr=$itemOutput.Split('#')
                if($itemOutput.Contains($res.Operation)){
                    $uniqItem[$res.ItemType]=$itemArr[0]+'#'+[String]([int]$itemArr[1]+1)
                }else{
                    $uniqItem[$res.ItemType]= $itemArr[0]+','+$res.Operation+'#'+[String]([int]$itemArr[1]+1)
                } 
            }else{
                $uniqItem.Add($res.ItemType,$res.Operation+'#'+1)
            }

                if($uniqDestnatn.ContainsKey($res.SiteUrl)){
                    $destOutput=[String]$uniqDestnatn[$res.SiteUrl]
                    $destArr=$destOutput.Split('#')
                    if($destOutput.Contains($res.Operation)){
                        $uniqDestnatn[$res.SiteUrl]=$destArr[0]+'#'+[String]([int]$destArr[1]+1)
                    }else{
                        $uniqDestnatn[$res.SiteUrl]= $destArr[0]+','+$res.Operation+'#'+[String]([int]$destArr[1]+1)
                    }
                }else{
                    $uniqDestnatn.Add($res.SiteUrl,$res.Operation+'#'+1)
                }

                if($uniqUsrAgent.ContainsKey($res.UserAgent)){
                    $uniqUsrAgent[$res.UserAgent]=[int]$uniqUsrAgent[$res.UserAgent]+1
                }else{
                    $uniqUsrAgent.Add($res.UserAgent,1)
                }

            if($fileAct.ContainsKey($res.Operation)){      
                $fileAct[$res.Operation]=[int]$fileAct[$res.Operation]+1
            }
        }

        #    ********** FOLDER OPERATIONS *******

        if($resFldr -ne "" -and $resFldr -ne $null){

            if($uniqFdrOpe.ContainsKey($resFldr.Operation)){
                $uniqFdrOpe[$resFldr.Operation]=[int]$uniqFdrOpe[$resFldr.Operation]+1
            }else{
                $uniqFdrOpe.Add($resFldr.Operation,1) 
            }

            $fldrUsrLine=$resFldr.UserId+'#'+$resFldr.ClientIP
            if($uniqFdrusers.ContainsKey($fldrUsrLine)){          
                $output=[String]$uniqFdrusers[$fldrUsrLine]
                $arr=$output.Split('#')
                if($output.Contains($resFldr.Operation)){
                    $uniqFdrusers[$fldrUsrLine]=$arr[0]+'#'+[String]([int]$arr[1]+1)
                }else{
                    $uniqFdrusers[$fldrUsrLine]= $arr[0]+','+$resFldr.Operation+'#'+[String]([int]$arr[1]+1)
                }               
            }else{
                $uniqFdrusers.Add($fldrUsrLine,$resFldr.Operation+'#'+1) 
            }

            if($uniqFdrClientIp.ContainsKey($resFldr.ClientIP)){
                $ipOutput=[String]$uniqFdrClientIp[$resFldr.ClientIP]
                $ipArr=$ipOutput.Split('#')
                if($ipOutput.Contains($resFldr.Operation)){
                    $uniqFdrClientIp[$resFldr.ClientIP]=$ipArr[0]+'#'+[String]([int]$ipArr[1]+1)
                }else{
                    $uniqFdrClientIp[$resFldr.ClientIP]= $ipArr[0]+','+$resFldr.Operation+'#'+[String]([int]$ipArr[1]+1)
                }               
            }else{
                $uniqFdrClientIp.Add($resFldr.ClientIP,$resFldr.Operation+'#'+1)
            }

            $fldrsiteLine=$resFldr.SiteUrl+'#'+$resFldr.Site
            if($uniqFdrsites.ContainsKey($fldrsiteLine)){
                $siteOutput=[String]$uniqFdrsites[$fldrsiteLine]
                $siteArr=$siteOutput.Split('#')
                if($siteOutput.Contains($resFldr.Operation)){
                    $uniqFdrsites[$fldrsiteLine]=$siteArr[0]+'#'+[String]([int]$siteArr[1]+1)
                }else{
                    $uniqFdrsites[$fldrsiteLine]= $siteArr[0]+','+$resFldr.Operation+'#'+[String]([int]$siteArr[1]+1)
                } 
            }else{
                $uniqFdrsites.Add($fldrsiteLine,$resFldr.Operation+'#'+1)
            }

            if($uniqFdrItem.ContainsKey($resFldr.ItemType)){
                $itemOutput=[String]$uniqFdrItem[$resFldr.ItemType]
                $itemArr=$itemOutput.Split('#')
                if($itemOutput.Contains($resFldr.Operation)){
                    $uniqFdrItem[$resFldr.ItemType]=$itemArr[0]+'#'+[String]([int]$itemArr[1]+1)
                }else{
                    $uniqFdrItem[$resFldr.ItemType]= $itemArr[0]+','+$resFldr.Operation+'#'+[String]([int]$itemArr[1]+1)
                } 
            }else{
                $uniqFdrItem.Add($resFldr.ItemType,$resFldr.Operation+'#'+1)
            }

            if($uniqFdrDestnatn.ContainsKey($resFldr.SiteUrl)){
                $destOutput=[String]$uniqFdrDestnatn[$resFldr.SiteUrl]
                $destArr=$destOutput.Split('#')
                if($destOutput.Contains($resFldr.Operation)){
                    $uniqFdrDestnatn[$resFldr.SiteUrl]=$destArr[0]+'#'+[String]([int]$destArr[1]+1)
                }else{
                    $uniqFdrDestnatn[$resFldr.SiteUrl]= $destArr[0]+','+$resFldr.Operation+'#'+[String]([int]$destArr[1]+1)
                }
            }else{
                $uniqFdrDestnatn.Add($resFldr.SiteUrl,$resFldr.Operation+'#'+1)
            }

            if($uniqFdUsrAgent.ContainsKey($resFldr.UserAgent)){
                $uniqFdUsrAgent[$resFldr.UserAgent]=[int]$uniqFdUsrAgent[$resFldr.UserAgent]+1
            }else{
                $uniqFdUsrAgent.Add($resFldr.UserAgent,1)
            }
     
            if($folderAct.ContainsKey($resFldr.Operation)){      
                $folderAct[$resFldr.Operation]=[int]$folderAct[$resFldr.Operation]+1
            }       
        }

        #    ********** SYNC OPERATIONS ********

        if($resSync -ne "" -and $resSync -ne $null){  

            if($uniqSyncOpe.ContainsKey($resSync.Operation)){
                $uniqSyncOpe[$resSync.Operation]=[int]$uniqSyncOpe[$resSync.Operation]+1
            }else{
                $uniqSyncOpe.Add($resSync.Operation,1) 
            }

            $syncUsrLine=$resSync.UserId+'#'+$resSync.ClientIP
            if($uniqSyncUsers.ContainsKey($syncUsrLine)){          
                $output=[String]$uniqSyncUsers[$syncUsrLine]
                $arr=$output.Split('#')
                if($output.Contains($resSync.Operation)){
                    $uniqSyncUsers[$syncUsrLine]=$arr[0]+'#'+[String]([int]$arr[1]+1)
                }else{
                    $uniqSyncUsers[$syncUsrLine]= $arr[0]+','+$resSync.Operation+'#'+[String]([int]$arr[1]+1)
                }               
            }else{
                $uniqSyncUsers.Add($syncUsrLine,$resSync.Operation+'#'+1) 
            }

            if($uniqSyncClientIp.ContainsKey($resSync.ClientIP)){
                $ipOutput=[String]$uniqSyncClientIp[$resSync.ClientIP]
                $ipArr=$ipOutput.Split('#')
                if($ipOutput.Contains($resSync.Operation)){
                    $uniqSyncClientIp[$resSync.ClientIP]=$ipArr[0]+'#'+[String]([int]$ipArr[1]+1)
                }else{
                    $uniqSyncClientIp[$resSync.ClientIP]= $ipArr[0]+','+$resSync.Operation+'#'+[String]([int]$ipArr[1]+1)
                }               
            }else{
                $uniqSyncClientIp.Add($resSync.ClientIP,$resSync.Operation+'#'+1)
            }

            $syncsiteLine=$resSync.SiteUrl+'#'+$resSync.Site
            if($uniqSyncSites.ContainsKey($syncsiteLine)){
                $siteOutput=[String]$uniqSyncSites[$syncsiteLine]
                $siteArr=$siteOutput.Split('#')
                if($siteOutput.Contains($resSync.Operation)){
                    $uniqSyncSites[$syncsiteLine]=$siteArr[0]+'#'+[String]([int]$siteArr[1]+1)
                }else{
                    $uniqSyncSites[$syncsiteLine]= $siteArr[0]+','+$resSync.Operation+'#'+[String]([int]$siteArr[1]+1)
                } 
            }else{
                $uniqSyncSites.Add($syncsiteLine,$resSync.Operation+'#'+1)
            }

            if($uniqSyncItem.ContainsKey($resSync.ItemType)){
                $itemOutput=[String]$uniqSyncItem[$resSync.ItemType]
                $itemArr=$itemOutput.Split('#')
                if($itemOutput.Contains($resSync.Operation)){
                    $uniqSyncItem[$resSync.ItemType]=$itemArr[0]+'#'+[String]([int]$itemArr[1]+1)
                }else{
                    $uniqSyncItem[$resSync.ItemType]= $itemArr[0]+','+$resSync.Operation+'#'+[String]([int]$itemArr[1]+1)
                } 
            }else{
                $uniqSyncItem.Add($resSync.ItemType,$resSync.Operation+'#'+1)
            }

            if($uniqSyncDestnatn.ContainsKey($resSync.SiteUrl)){
                $destOutput=[String]$uniqSyncDestnatn[$resSync.SiteUrl]
                $destArr=$destOutput.Split('#')
                if($destOutput.Contains($resSync.Operation)){
                    $uniqSyncDestnatn[$resSync.SiteUrl]=$destArr[0]+'#'+[String]([int]$destArr[1]+1)
                }else{
                    $uniqSyncDestnatn[$resSync.SiteUrl]= $destArr[0]+','+$resSync.Operation+'#'+[String]([int]$destArr[1]+1)
                }
            }else{
                $uniqSyncDestnatn.Add($resSync.SiteUrl,$resSync.Operation+'#'+1)
            }

            if($uniqSyncUsrAgent.ContainsKey($resSync.UserAgent)){
                $uniqSyncUsrAgent[$resSync.UserAgent]=[int]$uniqSyncUsrAgent[$resSync.UserAgent]+1
            }else{
                $uniqSyncUsrAgent.Add($resSync.UserAgent,1)
            }

            if($syncAct.ContainsKey($resSync.Operation)){          
                $syncAct[$resSync.Operation]=[int]$syncAct[$resSync.Operation]+1
            }  
        }

        #    ********** SHARING OPERATIONS ********

        if($resShrg -ne "" -and $resShrg -ne $null){

            if($uniqShrOpe.ContainsKey($resShrg.Operation)){
                $uniqShrOpe[$resShrg.Operation]=[int]$uniqShrOpe[$resShrg.Operation]+1
            }else{
                $uniqShrOpe.Add($resShrg.Operation,1) 
            }

            $shrgUsrLine=$resShrg.UserId+'#'+$resShrg.ClientIP
            if($uniqShrUsers.ContainsKey($shrgUsrLine)){          
                $output=[String]$uniqShrUsers[$shrgUsrLine]
                $arr=$output.Split('#')
                if($output.Contains($resShrg.Operation)){
                    $uniqShrUsers[$shrgUsrLine]=$arr[0]+'#'+[String]([int]$arr[1]+1)
                }else{
                    $uniqShrUsers[$shrgUsrLine]= $arr[0]+','+$resShrg.Operation+'#'+[String]([int]$arr[1]+1)
                }               
            }else{
                $uniqShrUsers.Add($shrgUsrLine,$resShrg.Operation+'#'+1) 
            }

            if($uniqShrClientIp.ContainsKey($resShrg.ClientIP)){
                $ipOutput=[String]$uniqShrClientIp[$resShrg.ClientIP]
                $ipArr=$ipOutput.Split('#')
                if($ipOutput.Contains($resShrg.Operation)){
                    $uniqShrClientIp[$resShrg.ClientIP]=$ipArr[0]+'#'+[String]([int]$ipArr[1]+1)
                }else{
                    $uniqShrClientIp[$resShrg.ClientIP]= $ipArr[0]+','+$resShrg.Operation+'#'+[String]([int]$ipArr[1]+1)
                }               
            }else{
                $uniqShrClientIp.Add($resShrg.ClientIP,$resShrg.Operation+'#'+1)
            }

            $shrgsiteLine=$resShrg.SiteUrl+'#'+$resShrg.Site
            if($uniqShrSites.ContainsKey($shrgsiteLine)){
                $siteOutput=[String]$uniqShrSites[$shrgsiteLine]
                $siteArr=$siteOutput.Split('#')
                if($siteOutput.Contains($resShrg.Operation)){
                    $uniqShrSites[$shrgsiteLine]=$siteArr[0]+'#'+[String]([int]$siteArr[1]+1)
                }else{
                    $uniqShrSites[$shrgsiteLine]= $siteArr[0]+','+$resShrg.Operation+'#'+[String]([int]$siteArr[1]+1)
                } 
            }else{
                $uniqShrSites.Add($shrgsiteLine,$resShrg.Operation+'#'+1)
            }

            if($uniqShrItem.ContainsKey($resShrg.ItemType)){
                $itemOutput=[String]$uniqShrItem[$resShrg.ItemType]
                $itemArr=$itemOutput.Split('#')
                if($itemOutput.Contains($resShrg.Operation)){
                    $uniqShrItem[$resShrg.ItemType]=$itemArr[0]+'#'+[String]([int]$itemArr[1]+1)
                }else{
                    $uniqShrItem[$resShrg.ItemType]= $itemArr[0]+','+$resShrg.Operation+'#'+[String]([int]$itemArr[1]+1)
                } 
            }else{
                $uniqShrItem.Add($resShrg.ItemType,$resShrg.Operation+'#'+1)
            }

            if($uniqShrDestnatn.ContainsKey($resShrg.SiteUrl)){
                $destOutput=[String]$uniqShrDestnatn[$resShrg.SiteUrl]
                $destArr=$destOutput.Split('#')
                if($destOutput.Contains($resShrg.Operation)){
                    $uniqShrDestnatn[$resShrg.SiteUrl]=$destArr[0]+'#'+[String]([int]$destArr[1]+1)
                }else{
                    $uniqShrDestnatn[$resShrg.SiteUrl]= $destArr[0]+','+$resShrg.Operation+'#'+[String]([int]$destArr[1]+1)
                }
            }else{
                $uniqShrDestnatn.Add($resShrg.SiteUrl,$resShrg.Operation+'#'+1)
            }   

            if($uniqShrUsrAgent.ContainsKey($resShrg.UserAgent)){
                $uniqShrUsrAgent[$resShrg.UserAgent]=[int]$uniqShrUsrAgent[$resShrg.UserAgent]+1
            }else{
                $uniqShrUsrAgent.Add($resShrg.UserAgent,1)
            }
     
            if($sharngAct.ContainsKey($resShrg.Operation)){               
                $sharngAct[$resShrg.Operation]=[int]$sharngAct[$resShrg.Operation]+1
            }
   
        }

        # ************** SITE ADMIN OPERATIONS ****************

        if($resSAdm -ne "" -and $resSAdm -ne $null){

            $isAdmUserAgent=[bool]($resSAdm.PSobject.Properties.name -match "UserAgent")
             $isAdmSiteUrl=[bool]($resSAdm.PSobject.Properties.name -match "SiteUrl")
        
            if($uniqAdmnOpe.ContainsKey($resSAdm.Operation)){
                $uniqAdmnOpe[$resSAdm.Operation]=[int]$uniqAdmnOpe[$resSAdm.Operation]+1
            }else{
                $uniqAdmnOpe.Add($resSAdm.Operation,1) 
            }

            $admnUsrLine=$resSAdm.UserId+'#'+$resSAdm.ClientIP
            if($uniqAdmnUsers.ContainsKey($admnUsrLine)){          
                $output=[String]$uniqAdmnUsers[$admnUsrLine]
                $arr=$output.Split('#')
                if($output.Contains($resSAdm.Operation)){
                    $uniqAdmnUsers[$admnUsrLine]=$arr[0]+'#'+[String]([int]$arr[1]+1)
                }else{
                    $uniqAdmnUsers[$admnUsrLine]= $arr[0]+','+$resSAdm.Operation+'#'+[String]([int]$arr[1]+1)
                }               
            }else{
                $uniqAdmnUsers.Add($admnUsrLine,$resSAdm.Operation+'#'+1) 
            }

            if($uniqAdmnClientIp.ContainsKey($resSAdm.ClientIP)){
                $ipOutput=[String]$uniqAdmnClientIp[$resSAdm.ClientIP]
                $ipArr=$ipOutput.Split('#')
                if($ipOutput.Contains($resSAdm.Operation)){
                    $uniqAdmnClientIp[$resSAdm.ClientIP]=$ipArr[0]+'#'+[String]([int]$ipArr[1]+1)
                }else{
                    $uniqAdmnClientIp[$resSAdm.ClientIP]= $ipArr[0]+','+$resSAdm.Operation+'#'+[String]([int]$ipArr[1]+1)
                }               
            }else{
                $uniqAdmnClientIp.Add($resSAdm.ClientIP,$resSAdm.Operation+'#'+1)
            }

            if($isAdmSiteUrl){
                $admnsiteLine=$resSAdm.SiteUrl+'#'+$resSAdm.Site
            }else{
                $admnsiteLine='-#'+$resSAdm.Site
            }
            if($uniqAdmnSites.ContainsKey($admnsiteLine)){
                $siteOutput=[String]$uniqAdmnSites[$admnsiteLine]
                $siteArr=$siteOutput.Split('#')
                if($siteOutput.Contains($resSAdm.Operation)){
                    $uniqAdmnSites[$admnsiteLine]=$siteArr[0]+'#'+[String]([int]$siteArr[1]+1)
                }else{
                    $uniqAdmnSites[$admnsiteLine]= $siteArr[0]+','+$resSAdm.Operation+'#'+[String]([int]$siteArr[1]+1)
                } 
            }else{
                $uniqAdmnSites.Add($admnsiteLine,$resSAdm.Operation+'#'+1)
            }

            if($uniqAdmnItem.ContainsKey($resSAdm.ItemType)){
                $itemOutput=[String]$uniqAdmnItem[$resSAdm.ItemType]
                $itemArr=$itemOutput.Split('#')
                if($itemOutput.Contains($resSAdm.Operation)){
                    $uniqAdmnItem[$resSAdm.ItemType]=$itemArr[0]+'#'+[String]([int]$itemArr[1]+1)
                }else{
                    $uniqAdmnItem[$resSAdm.ItemType]= $itemArr[0]+','+$resSAdm.Operation+'#'+[String]([int]$itemArr[1]+1)
                } 
            }else{
                $uniqAdmnItem.Add($resSAdm.ItemType,$resSAdm.Operation+'#'+1)
            }

            if($isAdmSiteUrl){
                if($uniqAdmnDestnatn.ContainsKey($resSAdm.SiteUrl)){
                    $destOutput=[String]$uniqAdmnDestnatn[$resSAdm.SiteUrl]
                        $destArr=$destOutput.Split('#')
                    if($destOutput.Contains($resSAdm.Operation)){
                        $uniqAdmnDestnatn[$resSAdm.SiteUrl]=$destArr[0]+'#'+[String]([int]$destArr[1]+1)
                    }else{
                        $uniqAdmnDestnatn[$resSAdm.SiteUrl]= $destArr[0]+','+$resSAdm.Operation+'#'+[String]([int]$destArr[1]+1)
                    }
                }else{
                    $uniqAdmnDestnatn.Add($resSAdm.SiteUrl,$resSAdm.Operation+'#'+1)
                }
            }

            if($isAdmUserAgent){
                if($uniqAdmnUsrAgent.ContainsKey($resSAdm.UserAgent)){
                    $uniqAdmnUsrAgent[$resSAdm.UserAgent]=[int]$uniqAdmnUsrAgent[$resSAdm.UserAgent]+1
                }else{
                    $uniqAdmnUsrAgent.Add($resSAdm.UserAgent,1)
                }
            }
      
            if($siteAdminAct.ContainsKey($resSAdm.Operation)){    
                $siteAdminAct[$resSAdm.Operation]=[int]$siteAdminAct[$resSAdm.Operation]+1
            }
        }

    }



    # ******* FILE OPERATIONS *********

    $fileOperCnt=""
    for($i=0;$i -lt $fileOpe.Length;$i++ ){
        $fileOperCnt+="~!~"+$fileAct[$fileOpe[$i]]
    }
    Write-Host "FilePage Operations Count"$fileOperCnt !>

    #Summary measure count values
    foreach($key in $uniqOpe.keys){
        Write-Host "FilePageOpeartion"~!~ $key ~!~ $uniqOpe[$key] !>
    }

    foreach($key in $uniqusers.keys){
        Write-Host "FilePageUsers"~!~ $key '#' $uniqusers[$key] !>
    }

    foreach($key in $uniqClientIp.keys){
        Write-Host "FilePageClientIP #"$key '#' $uniqClientIp[$key] !>
    }

    foreach($key in $uniqsites.keys){
        Write-Host "FilePageSites #"$key '#' $uniqsites[$key] !>
    }

    foreach($key in $uniqItem.keys){
        Write-Host "FilePageitems #"$key '#' $uniqItem[$key] !>
    }
    
    foreach($key in $uniqDestnatn.keys){
        Write-Host "FilePageDestination #"$key '#' $uniqDestnatn[$key] !>
    }

    foreach($key in $uniqUsrAgent.keys){
        Write-Host "FilePageUserAgent"~!~ $key~!~ $uniqUsrAgent[$key] !>
    }

    #    ********** FOLDER OPERATIONS *******

    $fldrOperCnt=""
    for($i=0;$i -lt $folderOpe.Length;$i++ ){   
        $fldrOperCnt+="~!~"+$folderAct[$folderOpe[$i]]
    }
    Write-Host "Folder Operations Count"$fldrOperCnt !>

    foreach($key in $uniqFdrOpe.keys){
        Write-Host "FolderOpeartion"~!~ $key ~!~ $uniqFdrOpe[$key] !>
    }

    foreach($key in $uniqFdrusers.keys){
        Write-Host "FolderUsers"~!~ $key '#' $uniqFdrusers[$key] !>
    }

    foreach($key in $uniqFdrClientIp.keys){
        Write-Host "FolderClientIP #" $key '#' $uniqFdrClientIp[$key] !>
    }

    foreach($key in $uniqFdrsites.keys){
        Write-Host "FolderSites #" $key '#' $uniqFdrsites[$key] !>
    }

    foreach($key in $uniqFdrItem.keys){
        Write-Host "Folderitems #" $key '#' $uniqFdrItem[$key] !>
    }

    foreach($key in $uniqFdrDestnatn.keys){
        Write-Host "FolderDestination #" $key '#' $uniqFdrDestnatn[$key] !>
    }

    foreach($key in $uniqFdUsrAgent.keys){
        Write-Host "FolderUserAgent"~!~ $key~!~ $uniqFdUsrAgent[$key] !>
    }


    #    ********** SYNC OPERATIONS ********


    $syncOperCnt=""
    for($i=0;$i -lt $syncOpe.Length;$i++ ){
        $syncOperCnt+="~!~"+$syncAct[$syncOpe[$i]]
    }
    Write-Host "Synchronization Operations Count"$syncOperCnt !>

    foreach($key in $uniqSyncOpe.keys){
        Write-Host "SyncOpeartion"~!~ $key ~!~ $uniqSyncOpe[$key] !>
    }

    foreach($key in $uniqSyncUsers.keys){
        Write-Host "SyncUsers"~!~ $key '#' $uniqSyncUsers[$key] !>
    }

    foreach($key in $uniqSyncClientIp.keys){
        Write-Host "SyncClientIP #" $key '#' $uniqSyncClientIp[$key] !>
    }

    foreach($key in $uniqSyncSites.keys){
        Write-Host "SyncSites #"$key '#' $uniqSyncSites[$key] !>
    }

    foreach($key in $uniqSyncItem.keys){
        Write-Host "Syncitems #"$key '#' $uniqSyncItem[$key] !>
    }

    foreach($key in $uniqSyncDestnatn.keys){
        Write-Host "SyncDestination #"$key '#' $uniqSyncDestnatn[$key] !>
    }

    foreach($key in $uniqSyncUsrAgent.keys){
        Write-Host "SyncUserAgent"~!~ $key~!~ $uniqSyncUsrAgent[$key] !>
    }


    #    ********** SHARING OPERATIONS ******** 

    $shrOperCnt=""
     for($i=0;$i -lt $sharngOpe.Length;$i++ ){  
         $shrOperCnt+="~!~"+$sharngAct[$sharngOpe[$i]]
     }
     Write-Host "Sharng Operations Count"$shrOperCnt !>
 
    foreach($key in $uniqShrOpe.keys){
        Write-Host "SharngOpeartion"~!~ $key ~!~ $uniqShrOpe[$key] !>
    }

    foreach($key in $uniqShrUsers.keys){
        Write-Host "SharngUsers"~!~ $key '#' $uniqShrUsers[$key] !>
    }

    foreach($key in $uniqShrClientIp.keys){
        Write-Host "SharngClientIP #"$key '#' $uniqShrClientIp[$key] !>
    }

    foreach($key in $uniqShrSites.keys){
        Write-Host "SharngSites #"$key '#' $uniqShrSites[$key] !>
    }

    foreach($key in $uniqShrItem.keys){
        Write-Host "Sharngitems #"$key '#' $uniqShrItem[$key] !>
    }

    foreach($key in $uniqShrDestnatn.keys){
        Write-Host "SharngDestination #"$key '#' $uniqShrDestnatn[$key] !>
    }

    foreach($key in $uniqShrUsrAgent.keys){
        Write-Host "SharngUserAgent"~!~ $key~!~ $uniqShrUsrAgent[$key] !>
    }

    # ************** SITE ADMIN OPERATIONS ****************

    $siteAdminOperCnt=""
    for($i=0;$i -lt $siteAdminOpe.Length;$i++ ){  
        $siteAdminOperCnt+="~!~"+$siteAdminAct[$siteAdminOpe[$i]]
    }
    Write-Host "SAdmin Operations Count"$siteAdminOperCnt !>
 
    foreach($key in $uniqAdmnOpe.keys){
        Write-Host "SAdminOpeartion"~!~ $key ~!~ $uniqAdmnOpe[$key] !>
    }

    foreach($key in $uniqAdmnUsers.keys){
        Write-Host "SAdminUsers"~!~ $key '#' $uniqAdmnUsers[$key] !>
    }

    foreach($key in $uniqAdmnClientIp.keys){
        Write-Host "SAdminClientIP #"$key '#' $uniqAdmnClientIp[$key] !>
    }

    foreach($key in $uniqAdmnSites.keys){
        Write-Host "SAdminSites #"$key '#' $uniqAdmnSites[$key] !>
    }

    foreach($key in $uniqAdmnItem.keys){
        Write-Host "SAdminitems #"$key '#' $uniqAdmnItem[$key] !>
    }

    foreach($key in $uniqAdmnDestnatn.keys){
        Write-Host "SAdminDestination #"$key '#' $uniqAdmnDestnatn[$key] !>
    }

    foreach($key in $uniqAdmnUsrAgent.keys){
        Write-Host "SAdminUserAgent"~!~ $key~!~ $uniqAdmnUsrAgent[$key] !>
    }

}
Catch{
    Write-Host 'Exception Occured in SPO Activity operation - ' $_.Exception.Message !>
}
Remove-Item $filePath -Force
Remove-Item $kfilePath -Force
#         *************************** END *************************

