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

$TestInputs=$args
$reportingname=$TestInputs[0]
$username=$TestInputs[1]
$password=Eg-O365Dcr -EncStr $TestInputs[2]
$proxyCrdlserver=$TestInputs[3].ToString().Split('#')
$proxyUser=$proxyCrdlserver[0]
$proxyPass=Eg-O365Dcr -EncStr $proxyCrdlserver[1]
$proxyserverip=$proxyCrdlserver[2]
$inputRptDat=$TestInputs[4]
$proxyserver=$proxyserver='http://'+$proxyserverip

$domain=Eg-GetDomain -userName $username -Password $password -proxyUsr $proxyUser -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver
$azureVal=Eg-GetAzureEnv -UserName $username -subject 'O365_Graph'
$azureEnvArr=$azureVal.Split(',')

$rptPath=$egurkhaPath+'\agent\SBO\'+$reportingname
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

$WriteLog=$true
$LogFile = $rptPath+"\sboreports.log"
$LogFile1 = $rptPath+"\sboreports1.log"
$isFrstTimLog=$true

# Writes output to a log file with a time date stamp
Function Write-Log {
	Param ([string]$string)

	[string]$date = Get-Date -Format G
	
    if ($WriteLog) {
       ( "[" + $date + "] - [" + $reportingname+"] mTime -  " + $mTime + " - " + $string ) | Out-File -FilePath $LogFile -Append } 

    if($isFrstTimLog){     
        if ($WriteLog -eq $true){ #if flag is true 
            if ([System.IO.File]::Exists($LogFile) -and (Get-Item $LogFile).length -gt 2mb) {  #if the size of file is greater than 1MB 
                if([System.IO.File]::Exists($LogFile1)){  #if logfile1 already exists, delete logfile1 
                    Remove-Item $LogFile1 
                } 
                Rename-Item $LogFile $LogFile1 
            }
        }
        $isFrstTimLog=$false
    }

}

Function Eg-InvokeUrl(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [String]$Url, 
        [Parameter(Mandatory=$true, Position=2)]
        [String]$filePath
        
    )

    Process
    {
        $creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $appId, $appSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
        $context = $authContext.AcquireTokenAsync($Resource, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()

        $header = @{
            'Authorization'=$authCode
        }
        
        $query = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
        $query=$query.Replace('ï»¿','')
        $query=$query.Replace(' ','')

        $resultarray = ConvertFrom-Csv -InputObject $query
        $reprts=$resultarray | ConvertTo-Json 
        $jsonreprt=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json

        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){  
            $reports.Usage[$i] |Export-Csv $filePath -Append -NoTypeInformation -Force
        } 
    }
}

Write-Log ".........Started Running the Script........."
$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$deviceusagecsv = $rptPath+'\DeviceUsagereport'+$timenow+'.csv'
try{
$authString=$azureEnvArr[0]+$domain
$Resource=$azureEnvArr[1]
$msGraphPath=$egurkhaPath+"\agent\O365\MsGraph"
$keyFileNam = '\GraphDetailsKey.dat'

$unProtPath= $msGraphPath+'\GraphDetails.dat'
$kvalue= Get-Content -Path $msGraphPath$keyFileNam
$null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.txt'

$SkypeInput=$msGraphPath+"\GraphDetails.txt"
$GetInput = Get-Content -Path $SkypeInput
}catch{
    Write-Log "File not found. The $GetInput location does not contain GraphDetails "
}
$flag=$false

    foreach($inp in $GetInput){
        if($inp.StartsWith('[') -and $inp.Contains($domain)){
            $flag=$true
        }
        if($flag){
            if($inp.Contains("client_id")){
                $appId =$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("client_secret")){
                $appSecret =$inp.ToString().Substring($inp.IndexOf('~')+1)
                $flag=$false
            }
            if($inp.Contains("TenantName")){
                $tenantID=$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("Authority")){
                $authString = $inp.ToString().Substring($inp.IndexOf('~')+1)
                $authString=$authString+$domain
            }
            if($inp.Contains("Resource")){
                $Resource =$inp.ToString().Substring($inp.IndexOf('~')+1)
                $flag=$false
            }
        }
    }

#$sysDate = (Get-Date).AddDays($ReportRefreshDate).ToString("yyyy-MM-dd")
#$sysDate = (Get-Date).AddDays(-2).ToString("yyyy-MM-dd")
$path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $path
<#
$actvtcntsurl = "https://graph.microsoft.com/v1.0/reports/getSkypeForBusinessActivityCounts(period='D7')"
Eg-InvokeUrl -Url $actvtcntsurl -filePath $activecntcsv
try{
$SkyActcnt= import-csv $activecntcsv
}catch{
Write-Log "File not found. The $reportingname location does not contain Activecount report"
}
    $Totpeertopeercnt = 0
    $Totorganizedcnt = 0
    $TotParticipatedcnt = 0

    foreach($skypeActivecnt in $SkyActcnt){
        if($skypeActivecnt.ReportDate -eq $inputRptDat){
            $Totpeertopeercnt += $skypeActivecnt.'Peer-to-peer'
            $Totorganizedcnt += $skypeActivecnt.Organized
            $TotParticipatedcnt += $skypeActivecnt.Participated
        }
    }
#>
$devicusgeurl = $azureEnvArr[2]+"reports/getSkypeForBusinessDeviceUsageDistributionUserCounts(period='D7')"
Eg-InvokeUrl -Url $devicusgeurl -filePath $deviceusagecsv
try{
    $SkyDevUsg= import-csv $deviceusagecsv
    Write-Log "created the deviceusagecsv file and processing"
}catch{
    Write-Log "File not found. The $reportingname location does not contain deviceusage report "
}

<#
$usrdetilurl = "https://graph.microsoft.com/v1.0/reports/getSkypeForBusinessActivityUserDetail(Date=$inputRptDat)"   #Date=$sysDate
Eg-InvokeUrl -Url $usrdetilurl -filePath $userdetilcsv
Write-Log ("Eg-InvokeUrl  usrdetilurl>>>>>" + $usrdetilurl + "<<<<<" )

try{
$SkyUsrDetail= import-csv $userdetilcsv
}catch{
	Write-Log "File not found. The $reportingname location does not contain userdetial report "
}

    $peertopimcnt = 0
    $peertopAudcnt = 0
    $peertopAudmincnt = 0
    $peertopvidcnt = 0
    $peertopvidmincnt = 0
    $peertopAppcnt = 0
    $peertopFletracnt = 0

    $orgconimcnt = 0
    $orgconAudvidcnt = 0
    $orgconAudvidmincnt = 0
    $orgconwebcnt = 0
    $orgcondial3partcnt = 0
    $orgcondialmscnt = 0
    $orgcondialinmsmincnt = 0
    $orgcondialoutmsmincnt = 0
    $orgconAppcnt = 0

    $parconimcnt = 0
    $parconAudvidcnt = 0
    $parconAudvidmincnt = 0
    $parconwebcnt = 0
    $parcondial3partcnt = 0
    $parconAppcnt = 0


    $SBOUsgReptHash = @{}

    $SBOUsgReptHash.Add('Peer-to-peerIM',@{})
    $SBOUsgReptHash.Add('Peer-to-peerAudio',@{})
    $SBOUsgReptHash.Add('Peer-to-peerAudioMinutes',@{})
    $SBOUsgReptHash.Add('Peer-to-peerVideo',@{})
    $SBOUsgReptHash.Add('Peer-to-peerVideoMinutes',@{})
    $SBOUsgReptHash.Add('Peer-to-peerAppSharing',@{})
    $SBOUsgReptHash.Add('Peer-to-peerFileTransfer',@{})

    $SBOUsgReptHash.Add('OrganizedConferenceIM',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceAudio/Video',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceAudio/VideoMinutes',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceWeb',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceDial-in/out3rdParty',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceDial-in/outMicrosoft',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceDial-inMicrosoftMinutes',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceDial-outMicrosoftMinutes',@{})
    $SBOUsgReptHash.Add('OrganizedConferenceAppSharing',@{})

    $SBOUsgReptHash.Add('ParticipatedConferenceIM',@{})
    $SBOUsgReptHash.Add('ParticipatedConferenceAudio/Video',@{})
    $SBOUsgReptHash.Add('ParticipatedConferenceAudio/VideoMinutes',@{})
    $SBOUsgReptHash.Add('ParticipatedConferenceWeb',@{})
    $SBOUsgReptHash.Add('ParticipatedConferenceDial-in/out3rdParty',@{})
    $SBOUsgReptHash.Add('ParticipatedConferenceAppSharing',@{})
    $reportDte=''
    $isTrue=$true
foreach($skypedetil in $SkyUsrDetail){ 
        #if($isTrue){
            $isTrue=$false
            $rptDat = $skypedetil.ReportRefreshDate
            $rplcCnt=$reportingname+'='+$inputRptDat
            $sboFilePath=$egurkhaPath+'/agent/SBO/'+$reportingname+'/SBODataFile.ini'
            if($rptDat -ne ''){    
                if(Test-Path $sboFilePath -PathType Leaf){
                    $val=''
                    Get-Content $sboFilePath | ForEach-Object{$rptVal=$_ -split '=';if($rptVal[0] -eq $reportingname){$val=$_}} 
                    if($val -ne ''){
                        (Get-Content $sboFilePath).replace($val,$rplcCnt) | Set-Content $sboFilePath
                    }
                }
            }
       # }
       
       $peertopimcnt += $skypedetil.'Peer-to-peerIMCount'
       $peertopAudcnt += $skypedetil.'Peer-to-peerAudioCount'
       $peertopAudmincnt += $skypedetil.'Peer-to-peerAudioMinutes'
       $peertopvidcnt += $skypedetil.'Peer-to-peerVideoCount'
       $peertopvidmincnt += $skypedetil.'Peer-to-peerVideoMinutes'
       $peertopAppcnt += $skypedetil.'Peer-to-peerAppSharingCount'
       $peertopFletracnt += $skypedetil.'Peer-to-peerFileTransferCount'

       $orgconimcnt += $skypedetil.'OrganizedConferenceIMCount'
       $orgconAudvidcnt += $skypedetil.'OrganizedConferenceAudio/VideoCount'
       $orgconAudvidmincnt += $skypedetil.'OrganizedConferenceAudio/VideoMinutes'
       $orgconwebcnt += $skypedetil.'OrganizedConferenceWebCount'
       $orgcondial3partcnt += $skypedetil.'OrganizedConferenceDial-in/out3rdPartyCount'
       $orgcondialmscnt += $skypedetil.'OrganizedConferenceDial-in/outMicrosoftCount'
       $orgcondialinmsmincnt += $skypedetil.'OrganizedConferenceDial-inMicrosoftMinutes'
       $orgcondialoutmsmincnt += $skypedetil.'OrganizedConferenceDial-outMicrosoftMinutes'
       $orgconAppcnt += $skypedetil.'OrganizedConferenceAppSharingCount'

       $parconimcnt += $skypedetil.ParticipatedConferenceIMCount
       $parconAudvidcnt += $skypedetil.'ParticipatedConferenceAudio/VideoCount'
       $parconAudvidmincnt += $skypedetil.'ParticipatedConferenceAudio/VideoMinutes'
       $parconwebcnt += $skypedetil.ParticipatedConferenceWebCount
       $parcondial3partcnt += $skypedetil.'ParticipatedConferenceDial-in/out3rdPartyCount'
       $parconAppcnt += $skypedetil.ParticipatedConferenceAppSharingCount

       $reportrefdte = $skypedetil.ReportRefreshDate
       $username = $skypedetil.UserPrincipalName
       $PeerLastActivityDate = $skypedetil.'Peer-to-peerLastActivityDate'
       $OrganizedConferenceLastActivityDate = $skypedetil.OrganizedConferenceLastActivityDate
       $ParticipatedConferenceLastActivityDate = $skypedetil.ParticipatedConferenceLastActivityDate
       $LastActivityDate = $skypedetil.LastActivityDate
       $IsDeleted = $skypedetil.IsDeleted
       $DeletedDate = $skypedetil.DeletedDate
       $AssignedProducts = $skypedetil.AssignedProducts

       if([int]$skypedetil.'Peer-to-peerIMCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerIMCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerIM'].Add($dd,[int]($skypedetil.'Peer-to-peerIMCount'))
       }
       if([int]$skypedetil.'Peer-to-peerAudioCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerAudioCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerAudio'].Add($dd,[int]($skypedetil.'Peer-to-peerAudioCount'))
       }
       if([int]$skypedetil.'Peer-to-peerAudioMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerAudioMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerAudioMinutes'].Add($dd,[int]($skypedetil.'Peer-to-peerAudioMinutes'))
       }
       if([int]$skypedetil.'Peer-to-peerVideoCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerVideoCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerVideo'].Add($dd,[int]($skypedetil.'Peer-to-peerVideoCount'))
       }
       if([int]$skypedetil.'Peer-to-peerVideoMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerVideoMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerVideoMinutes'].Add($dd,[int]($skypedetil.'Peer-to-peerVideoMinutes'))
       }
       if([int]$skypedetil.'Peer-to-peerAppSharingCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerAppSharingCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerAppSharing'].Add($dd,[int]($skypedetil.'Peer-to-peerAppSharingCount'))
       }
       if([int]$skypedetil.'Peer-to-peerFileTransferCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'Peer-to-peerFileTransferCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['Peer-to-peerFileTransfer'].Add($dd,[int]($skypedetil.'Peer-to-peerFileTransferCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceIMCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceIMCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceIM'].Add($dd,[int]($skypedetil.'OrganizedConferenceIMCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceAudio/VideoCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceAudio/VideoCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceAudio/Video'].Add($dd,[int]($skypedetil.'OrganizedConferenceAudio/VideoCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceAudio/VideoMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceAudio/VideoMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceAudio/VideoMinutes'].Add($dd,[int]($skypedetil.'OrganizedConferenceAudio/VideoMinutes'))
       }
       if([int]$skypedetil.'OrganizedConferenceWebCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceWebCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceWeb'].Add($dd,[int]($skypedetil.'OrganizedConferenceWebCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceDial-in/out3rdPartyCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceDial-in/out3rdPartyCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceDial-in/out3rdParty'].Add($dd,[int]($skypedetil.'OrganizedConferenceDial-in/out3rdPartyCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceDial-in/outMicrosoftCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceDial-in/outMicrosoftCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceDial-in/outMicrosoft'].Add($dd,[int]($skypedetil.'OrganizedConferenceDial-in/outMicrosoftCount'))
       }
       if([int]$skypedetil.'OrganizedConferenceDial-inMicrosoftMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceDial-inMicrosoftMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceDial-inMicrosoftMinutes'].Add($dd,[int]($skypedetil.'OrganizedConferenceDial-inMicrosoftMinutes'))
       }
       if([int]$skypedetil.'OrganizedConferenceDial-outMicrosoftMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceDial-outMicrosoftMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceDial-outMicrosoftMinutes'].Add($dd,[int]($skypedetil.'OrganizedConferenceDial-outMicrosoftMinutes'))
       }
       if([int]$skypedetil.'OrganizedConferenceAppSharingCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'OrganizedConferenceAppSharingCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['OrganizedConferenceAppSharing'].Add($dd,[int]($skypedetil.'OrganizedConferenceAppSharingCount'))
       }
       if([int]$skypedetil.ParticipatedConferenceIMCount -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.ParticipatedConferenceIMCount+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceIM'].Add($dd,[int]($skypedetil.ParticipatedConferenceIMCount))
       }
       if([int]$skypedetil.'ParticipatedConferenceAudio/VideoCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'ParticipatedConferenceAudio/VideoCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceAudio/Video'].Add($dd,[int]($skypedetil.'ParticipatedConferenceAudio/VideoCount'))
       }
       if([int]$skypedetil.'ParticipatedConferenceAudio/VideoMinutes' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'ParticipatedConferenceAudio/VideoMinutes'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceAudio/VideoMinutes'].Add($dd,[int]($skypedetil.'ParticipatedConferenceAudio/VideoMinutes'))
       }
       if([int]$skypedetil.ParticipatedConferenceWebCount -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.ParticipatedConferenceWebCount+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceWeb'].Add($dd,[int]($skypedetil.ParticipatedConferenceWebCount))
       }
       if([int]$skypedetil.'ParticipatedConferenceDial-in/out3rdPartyCount' -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.'ParticipatedConferenceDial-in/out3rdPartyCount'+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceDial-in/out3rdParty'].Add($dd,[int]($skypedetil.'ParticipatedConferenceDial-in/out3rdPartyCount'))
       }
       if([int]$skypedetil.ParticipatedConferenceAppSharingCount -gt 0){
       $dd= $reportrefdte+'~!~'+$username+'~!~'+$skypedetil.ParticipatedConferenceAppSharingCount+'~!~'+$PeerLastActivityDate+'~!~'+$OrganizedConferenceLastActivityDate+'~!~'+$ParticipatedConferenceLastActivityDate+'~!~'+$LastActivityDate+'~!~'+$IsDeleted+'~!~'+$DeletedDate+'~!~'+$AssignedProducts
       $SBOUsgReptHash['ParticipatedConferenceAppSharing'].Add($dd,[int]($skypedetil.ParticipatedConferenceAppSharingCount))
       }

}
    #Write-Host 'ReportDate:'$reportDte
    Write-Host '-------------Peet to Peer Sessions-------------'
    Write-Host 'peermeasure~' $peertopimcnt'~'$peertopAudcnt'~'$peertopAudmincnt'~'$peertopvidcnt'~'$peertopvidmincnt'~'$peertopAppcnt'~'$peertopFletracnt'~'$Totpeertopeercnt

        foreach($peer in $SBOUsgReptHash['Peer-to-peerIM'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#peerInstantsMsgsdd~!~'$peer.Key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerAudio'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peerAudiocalldd~!~'$peer.key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerAudioMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peerAudiomindd~!~'$peer.key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerVideo'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peervideocalldd~!~'$peer.Key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerVideoMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peervideomindd~!~'$peer.key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerAppSharing'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peerAppsharedd~!~'$peer.key
	    }
        foreach($peer in $SBOUsgReptHash['Peer-to-peerFileTransfer'].GetEnumerator() | sort -Property value -Descending | select -First 25 )
	    {
		    Write-Host '#peerfiletransdd~!~'$peer.key
	    }

    Write-Host '-------------Organized Confereneces-------------'
    Write-Host 'orgconmeasures~' $orgconimcnt'~'$orgconAudvidcnt'~'$orgconAudvidmincnt'~'$orgconwebcnt'~'$orgcondial3partcnt'~'$orgcondialmscnt'~'$orgcondialinmsmincnt'~'$orgcondialoutmsmincnt'~'$orgconAppcnt'~'$Totorganizedcnt

        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceIM'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgInstantsMsgsdd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceAudio/Video'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgAudiovideocalldd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceAudio/VideoMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgAudiovideomindd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceWeb'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgwebdd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceDial-in/out3rdParty'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgDialinout3dd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceDial-in/outMicrosoft'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgDialinoutmsdd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceDial-inMicrosoftMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgDialinmsmindd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceDial-outMicrosoftMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgDialoutmsmindd~!~'$orgcon.key
	    }
        foreach($orgcon in $SBOUsgReptHash['OrganizedConferenceAppSharing'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#orgAppsharedd~!~'$orgcon.key
	    }

    Write-Host '-------------participated Confereneces-------------'
    Write-Host 'parconmeasures~' $parconimcnt'~'$parconAudvidcnt'~'$parconAudvidmincnt'~'$parconwebcnt'~'$parcondial3partcnt'~'$parconAppcnt'~'$TotParticipatedcnt
        
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceIM'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parInstantsMsgsdd~!~'$parcon.key
	    }
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceAudio/Video'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parAudiovideocalldd~!~'$parcon.key
	    }
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceAudio/VideoMinutes'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parAudiovideomindd~!~'$parcon.key
	    }
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceWeb'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parwebdd~!~'$parcon.key
	    }
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceDial-in/out3rdParty'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parDialinout3dd~!~'$parcon.key
	    }
        foreach($parcon in $SBOUsgReptHash['ParticipatedConferenceAppSharing'].GetEnumerator() | sort -Property value -Descending | select -First 25)
	    {
		    Write-Host '#parAppsharedd~!~'$parcon.key
	    }
      $SBOUsgReptHash =$null
  #>  
    Write-Host '-------------Device Usage-------------'
   
   foreach($dev in $SkyDevUsg){
        $isFlag=$false
        $dev.PSObject.Properties | ForEach-Object{
            if($_.Name -eq 'ReportPeriod'){break}
            
            if($isFlag){
                $write='deviceinfo~ '+$_.Name+' ~ '+$_.Value
                Write-Host $write  
            }

            if($_.Name -eq 'ReportRefreshDate'){$isFlag=$true}
        }
  }

<#

    if(Test-Path -Path $SkypeInput){
    Write-Log (" inside SkypeInput csv remove path" )
        Remove-Item $SkypeInput -Force
    }

    if($Error){ Write-Log $Error ;$Error.Clear()}
     
    if(Test-Path -Path $userdetilcsv){
    Write-Log (" inside userdetails csv remove path" )
        Remove-Item $userdetilcsv -Force
    }
    
    if($Error){ Write-Log $Error ;$Error.Clear()}
    
    if(Test-Path -Path $activecntcsv){
    Write-Log (" inside activecntcsv csv remove path" )
        Remove-Item $activecntcsv -Force
    }
  #>  
    if($Error){ Write-Log 'Error.... $Error' ;$Error.Clear()}
    
    if(Test-Path -Path $deviceusagecsv){
        Write-Log (" Removing the  deviceusagecsv file" )
        Remove-Item $deviceusagecsv -Force
    }
    if($Error){ Write-Log ('Error.... '+$Error ) ;$Error.Clear()} 
    Write-Log (".............Script completed.............." )