Collect-AMALogs.ps1

<#PSScriptInfo
 
.VERSION 1.0.0.2
 
.GUID 90906aef-550b-473a-a082-621450063a65
 
.AUTHOR maabusha
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
.PRIVATEDATA
 
#>


<#
 
.DESCRIPTION
 Collect Logs for Windows OMS Agent issues, Azure Update Managment and Hybrid worker.
 
#>
 
Param(
    [boolean]
    [Parameter(Mandatory = $false)]
    $CollectUpdate = $true,

    [boolean]
    [Parameter(Mandatory = $false)]
    $CollectETL = $true,

    [boolean]
    [Parameter(Mandatory = $false)]
    $CollectHybridSandbox = $true,

    [boolean]
    [Parameter(Mandatory = $false)]
    $CollectChangeTrackingLogs = $true,

    [int]
    [Parameter(Mandatory = $false)]
    $RefreshSleep = 60,
    
    [Int32]
    [Parameter(Mandatory = $false)]
    $WaitEvntId = -1
)

$ScriptVersion = '1.0.0.2'

# Write the script version
Write-Host ("Script version: {0}" -f $ScriptVersion)

# Write the command line that was used when the script was called
Write-Host ("Command line: {0}" -f $MyInvocation.Line)

# Get the current time in UTC
Write-Host ("Current UTC time: {0}" -f [System.DateTime]::UtcNow.ToString('yyyy-MM-dd HH:mm:ss'))


'Refresh cache and collect logs'
'########################################'
 
$hostname = $env:COMPUTERNAME
$timestamp = Get-Date -Format "yyyymmdd"
$randNumber = Get-Random
$resultPath = "c:\CaseLogs"
$tempPath = "$resultPath\Temp"
$opsMgrTracePath = "$tempPath\OpsMgrTrace"
$ChangeTrackingWorkPath = "$tempPath\ChangeTracking"
$CTChangeTractingPath = "$ChangeTrackingWorkPath\CT"
$FCTChangeTractingPath = "$ChangeTrackingWorkPath\FCT"


# OMS Agent Client Logs:
$OMSAgentInstallationPath = "C:\Program Files\Microsoft Monitoring Agent\Agent"
$OMSAgentToolsPath = "$OMSAgentInstallationPath\Tools"
$OMSAgentStatePath = "$OMSAgentInstallationPath\Health Service State"
$ETLDefaultPath = "C:\Windows\Logs\OpsMgrTrace\"
$SandboxPath = "C:\ProgramData\Microsoft\System Center\Orchestrator\7.2\SMA\Sandboxes"

Function CreateResultFolder {
    'Create folder structure'
    if (-Not (Test-Path $resultPath)) {
        New-Item -Path $resultPath -ItemType Directory
    }
 
    if (Test-Path $tempPath) {
        Remove-Item -Path  $tempPath  -Recurse -Force
            
    }

    New-Item -Path $tempPath -ItemType Directory
    if ($CollectETL) {
        New-Item -Path $opsMgrTracePath -ItemType Directory
    }

    if ($CollectChangeTrackingLogs) {
        New-Item -Path $ChangeTrackingWorkPath -ItemType Directory
        New-Item -Path $FCTChangeTractingPath -ItemType Directory
        New-Item -Path $CTChangeTractingPath -ItemType Directory
    }
}

function Find-EventId { 
    param(
        [DateTime]
        [Parameter(Mandatory = $true)]
        $startTime,

        [Int32]
        [Parameter(Mandatory = $true)]
        $eventId)

    Get-WinEvent -FilterHashtable @{logname = 'Operations Manager'; id = $eventId; StartTime = $startTime } | Measure-Object | % { $_.Count }
}
 
 
 
CreateResultFolder
 
Start-Transcript -Path "$tempPath\Transcript.txt"
 
'Stop HealthService'
net stop healthservice
 
'Rename health service state folder to refresh configruation and state'

Rename-Item -Path "$OMSAgentStatePath" -NewName "$OMSAgentStatePath.$randNumber"

if ($CollectETL) {
    'Collect ETL Trace'
    Set-Location $OMSAgentToolsPath

    .\Stoptracing.cmd
    .\Starttracing.cmd VER
 
}

$restartTime = Get-Date

'Start HealthService' 
net start healthservice
 
if ($WaitEvntId -gt 0 ) {
    "Sleeping for Event ID: $WaitEvntId to be log"
    $count = Find-EventId -startTime $restartTime -eventId $WaitEvntId
    while ($count -eq 0) {
        Start-Sleep 10
        $count = Find-EventId -startTime $restartTime -eventId $WaitEvntId
    }
}
else {
    "Sleeping for $RefreshSleep seconds waiting for refresh to happen"
    Start-Sleep -s $RefreshSleep
}


 
if ($CollectETL) {
    .\Stoptracing.cmd
    .\FormatTracing.cmd
    Copy-Item $ETLDefaultPath -Destination $opsMgrTracePath -recurse -Force
}
 
'Get Machine info'
systeminfo.exe > "$tempPath\case-$hostname-SystemInfo.txt"
 
'Test Cloud Connectivit'
Set-Location $OMSAgentInstallationPath
.\TestCloudConnection.exe | Set-Content "$tempPath\case-$hostname-TestCloudResult.txt"
 
 
 
'Get MMA information'
$Agent = get-itemproperty -path "HKLM:\SOFTWARE\Microsoft\Microsoft Operations Manager\3.0\Setup"
$mma = New-Object -ComObject 'AgentConfigManager.MgmtSvcCfg'
"MMA Current Version: " + $Agent.CurrentVersion | Set-Content "c:\CaseLogs\Temp\case-$hostname-MMAInfo.txt"
"ActiveDirectoryIntegrationEnabled: " + $mma.ActiveDirectoryIntegrationEnabled | Add-Content "$tempPath\case-$hostname-MMAInfo.txt"
"LocalCollectionEnabled: " + $mma.LocalCollectionEnabled | Add-Content "$tempPath\case-$hostname-MMAInfo.txt"
$workspaceID = $mma.GetCloudWorkspaces()[0].workspaceId
"workspaceId: " + $mma.GetCloudWorkspaces()[0].workspaceId | Add-Content "$tempPath\case-$hostname-MMAInfo.txt"
"ConnectionStatusText: " + $mma.GetCloudWorkspaces()[0].ConnectionStatusText | Add-Content "$tempPath\case-$hostname-MMAInfo.txt"
"Proxy: " + $mma.proxyUrl | Add-Content "$tempPath\case-$hostname-MMAInfo.txt"
 
 
"get WIndows Update Logs and Policy Registry key"
$windowsUpdateFile = $Env:WinDir + "\Windowsupdate.log"
# TODO: Windows Update - Check if OS is supported
if ($CollectUpdate) {
    if (Get-Command "Get-WindowsUpdateLog" -errorAction SilentlyContinue) {
        Get-WindowsUpdateLog -LogPath "$tempPath\Case-$hostname-WindowsUpdate.log"
    }
    else {
        Copy-Item $windowsUpdateFile -Destination "$tempPath\Case-$hostname-WindowsUpdate.log" -Force
    }
    

    # TODO: Get TRSOP result
    Reg export HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\  "$tempPath\case-$hostname-WindowsUpdatePolicyRegistery.txt"
    Reg export HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\  "$tempPath\case-$hostname-WindowsUpdateRegistery.txt"
}
 
 
'Get System, Application, OpsMgr and SMA logs'
wevtutil epl "Operations Manager" "$tempPath\case-%COMPUTERNAME%-Operations-Manager.evtx"
wevtutil epl "System" "$tempPath\case-%COMPUTERNAME%-System.evtx"
wevtutil epl "Application" "$tempPath\case-%COMPUTERNAME%-Application.evtx"
 
if ($CollectHybridSandbox) {
    wevtutil epl "Microsoft-SMA/Operational" "$tempPath\case-%COMPUTERNAME%-SMA.evtx "
    'Copy Hybrid workder Sandbox files'
    Copy-Item $SandboxPath -Destination '$tempPath' -recurse -Force
}
 
if ($CollectChangeTrackingLogs) {
    'Copy CT files'
    $countCT = Get-ChildItem "$OMSAgentStatePath\CT_*" | Measure-Object | % { $_.Count }
    $Retries = 10
    while (($countCT -eq 0) -and !($Retries -eq 0)) {
        'CT folder is not created yet'
        Start-Sleep 10
        $countCT = Get-ChildItem "$OMSAgentStatePath\CT_*" | Measure-Object | % { $_.Count }
        $Retries -= 1 
    }
    Get-ChildItem -Path "$OMSAgentStatePath\CT_*" | Copy-Item -Destination $CTChangeTractingPath -recurse -Force -Verbose

    $countFCT = Get-ChildItem "$OMSAgentStatePath\FCT_*" | Measure-Object | % { $_.Count }

    $Retries = 10
    while (($countFCT -eq 0) -and !($Retries -eq 0)) {
        'FCT folder is not created yet'
        Start-Sleep 10
        $countFCT = Get-ChildItem "$OMSAgentStatePath\FCT_*" | Measure-Object | % { $_.Count }
        $Retries -= 1 
    }
    'Copy FCT files'
    Get-ChildItem -Path "$OMSAgentStatePath\FCT_*" | Copy-Item -Destination $FCTChangeTractingPath -recurse -Force -Verbose
    
}

Stop-Transcript
Compress-Archive -Path c:\CaseLogs\Temp\* -DestinationPath "$resultPath\Caselogs-$timestamp.zip"
 
Remove-Item -Path $tempPath -Recurse
 
"Copy and upload $resultPath\Caselogs.zip to the Case WebDrive"