CCMLogs.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
function Read-LogEntry
{
    [CmdletBinding(ConfirmImpact = 'Low', SupportsShouldProcess = $False)]
    param
    (
        [Parameter(Mandatory = $True, HelpMessage = 'The log entry to be parsed')]
        [string] $InputObject,

        [Parameter(Mandatory = $False, HelpMessage = 'Drops entries that occurred after the specified date and time.')]
        [datetime] $After,

        [Parameter(Mandatory = $False, HelpMessage = 'Drops entries that occurred before the specified date and time.')]
        [datetime] $Before
    )

    if ($PSBoundParameters.ContainsKey('Debug'))
    {
        $DebugPreference = 'Continue'
    }

    Write-Debug -Message "Processing log entry: '$InputObject'"
    try
    {
        Write-Debug -Message 'Processing message property.'
        [string] $Message = ($InputObject | Select-String -Pattern '\[LOG\[((.| )+)\]LOG\]').Matches.Value
        # Identifies the message sections of each line using the [LOG[] tags and removes them for us.
        if ($Log -like 'AppIntentEval')
        {
            Write-Debug -Message 'Parsing AppIntentEval message.'
            $Message = $Message -replace ':- |, ', "`n"
            # Lazy reformatting to key:value statements instead of in a line.
        }
        $Message = ($Message -replace '\[LOG\[|\]LOG\]').Trim()
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }

    if (-not ($Message))
    {
        Write-Debug -Message 'Unable to read blank message - skipping to next.'
        Continue
    }

    try
    {
        Write-Debug -Message 'Processing metadata block.'
        [string] $Metadata = ((($InputObject | Select-String -Pattern '<time((.| )+)>').Matches.Value -replace '<|>') -split ' ')
        # Identifies and isolates the metadata section
        # Includes the time and date which we want, but also other entries which we'll need to get rid of.
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }

    try
    {
        Write-Debug -Message 'Processing TimeStub block.'
        [string] $TimeStub = ((($Metadata -split ' ')[0] -replace 'time|=|"') -split '\.')[0]
        # To find the time, we remove 'time', '=', and '"'
        # Split the remainder in two based on '.' and keep the first part.
        # This is a bit awkward but the casting is tricky without the split.
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }

    try
    {
        Write-Debug -Message 'Processing DateStub block.'
        [string] $DateStub = ((($Metadata -split ' ')[1] -replace 'date|=|"'))
        # Finding the date is similar but simpler.
        # We only need to remove 'date', '=', and '"'.
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }


    try
    {
        Write-Debug -Message 'Generating timestamp.'
        [datetime] $TimeStamp = "$DateStub $TimeStub"
        # At the end we add the two stubs together, and cast them as a [datetime] object
        # When the [datetime] object is constructed we can begin to filter based on a time range.
        if ($After)
        {
            if ($Timestamp -lt $After)
            {
                Write-Debug -Message "Timestamp is before '$After' cut-off."
                Continue
            }
        }
        if ($Before)
        {
            if ($Timestamp -gt $Before)
            {
                Write-Debug -Message "Timestamp is after '$Before' cut-off."
                Continue
            }
        }

        [PSCustomObject]@{
            Timestamp = $TimeStamp
            Message   = $Message
        }
    }
    catch
    {
        $PSCmdlet.ThrowTerminatingError($_)
    }
}

function Get-CCMLog
{
    <#
    .SYNOPSIS
        A simple utility to view Configuration Manager log files in Powershell.
    .DESCRIPTION
        Retrieves entries from Configuration Manager's log files (defaulting to the last 2000 lines per file) from a local or remote computer and converts them to objects.
    .PARAMETER LogName
        The name of the log(s) to be retrieved.
    .PARAMETER Path
        The directory the logs are stored in. UNC path's are assumed for use against remote machine but conversion from local drives is automatically attempted.
    .PARAMETER ComputerName
        The computer(s) whose logs will queried.
    .PARAMETER After
        Gets entries that occurred after a specified date and time.
    .PARAMETER Before
        Gets entries that occurred before a specified date and time.
    .PARAMETER Count
        The number of entries to be retrieved - this is calculated per computer/group of logs rather than per log.
    .EXAMPLE
        Get-CCMLog -LogName "AppDiscovery"

        Retrieves the AppDiscovery log of the local machine
    .EXAMPLE
        Get-CCMLog -LogName "AppDiscovery" -Count 10

        Retrieves a maximum of 10 entries from the AppDiscovery log of the local machine
    .EXAMPLE
        Get-CCMLog -LogName "AppDiscovery" -After (Get-Date).AddDays(-1)

        Retrieves the AppDiscovery log of the local machine for the last 24 hours
    .EXAMPLE
        Get-CCMLog -LogName AppEnforce -After "09:35:25 02 June 2020" -Before "11:35:28 02 June 2020"

        Retrieves the AppDiscovery log of the local machine for a specified 2 hour period
    .EXAMPLE
        Get-CCMLog -LogName "AppIntentEval", "AppDiscovery", "AppEnforce" | Out-GridView

        Retrieves the 'AppIntentEval', 'AppDiscovery' and 'AppEnforce' log entries and outputs to Out-GridView for interactive search and manipulation
    .EXAMPLE
        Get-CCMLog -LogName PolicyAgent, AppDiscovery, AppIntentEval, CAS, ContentTransferManager, DataTransferService, AppEnforce | Out-GridView

        Retrieves logs allowing for the tracing of a deployment from machine policy to app enforcement and outputs to Out-GridView again
    .INPUTS
        String
    .OUTPUTS
        PSCustomObject
    #>

    [CmdletBinding(ConfirmImpact = "Low", SupportsShouldProcess = $True, DefaultParameterSetName = "NamedLogs")]
    [OutputType("PSCustomObject")]
    param
    (
        [Parameter(Position = 0, ParameterSetName = "NamedLogs" , HelpMessage = "The log(s) to be retrieved")]
        [alias("Name")]
        [ValidateSet("AlternateHandler", "AppDiscovery", "AppEnforce", "AppIntentEval", "AssetAdvisor", "CAS", "Ccm32BitLauncher", "CcmCloud",
            "CcmEval", "CcmEvalTask", "CcmExec", "CcmMessaging", "CcmNotificationAgent", "CcmRepair", "CcmRestart", "CCMSDKProvider",
            "CCMSetup", "CcmSqlCE", "CCMVDIProvider", "CertEnrollAgent", "CertificateMaintenance", "CIAgent", "CIDownloader", "CIStateStore",
            "CIStore", "CITaskMgr", "ClientIDManagerStartup", "ClientLocation", "Client.Msi", "ClientServicing", "CMBITSManager", "CmRcService",
            "CoManagementHandler", "ComplRelayAgent", "ContentTransferManager", "DataTransferService", "DCMAgent", "DCMReporting",
            "DcmWmiProvider", "DdrProvider", "DeltaDownload", "EndpointProtectionAgent", "execmgr", "ExpressionSolver",
            "ExternalEventAgent", "FileBITS", "FSPStateMessage", "InternetProxy", "InventoryAgent", "InventoryProvider",
            "LocationServices", "MaintenanceCoordinator", "ManagedProvider", "mtrmgr", "oobmgmt", "PeerDPAgent", "PolicyAgent",
            "PolicyAgentProvider", "PolicyEvaluator", "pwrmgmt", "PwrProvider", "RebootCoordinator", "ScanAgent", "Scheduler",
            "ServiceWindowManager", "SettingsAgent", "setuppolicyevaluator", "smscliui", "SoftwareCatalogUpdateEndpoint",
            "SoftwareCenterSystemTasks", "SrcUpdateMgr", "StateMessage", "StateMessageProvider", "StatusAgent", "SWMTRReportGen",
            "UpdatesDeployment", "UpdatesHandler", "UpdatesStore", "UpdateTrustedSites", "UserAffinity", "UserAffinityProvider",
            "VirtualApp", "wedmtrace", "WindowsAnalytics", "WUAHandler")]
        [string[]] $LogName = "AppEnforce",

        [Parameter(Position = 0, ParameterSetName = "AllLogs", HelpMessage = "Indicates that all *.log files in the Path directory will be parsed")]
        [switch] $AllLogs = $False,

        [Parameter(Position = 1, HelpMessage = "The path to the directory containing the logs")]
        [string] $Path = "C:\Windows\CCM\Logs",

        [Parameter(Position = 2, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True, HelpMessage = "The computer whose logs will be parsed")]
        [alias("PSComputerName", "__SERVER", "CN", "IPAddress")]
        [string[]] $ComputerName = "localhost",

        [Parameter(HelpMessage = "Gets entries that occurred after a specified date and time.")]
        [datetime] $After,

        [Parameter(HelpMessage = "Gets entries that occurred before a specified date and time.")]
        [datetime] $Before,

        [Parameter(HelpMessage = "The number of entries to be retrieved.")]
        [int] $Count
    )

    BEGIN
    {
        if ($PSBoundParameters.ContainsKey("Debug"))
        {
            $DebugPreference = "Continue"
        }

        # A colleague encountered weird, broken behaviour if running this from a CMSite provider
        # To be safe, we're going to explicitly move to a FileSystem if not already in one
        if (($ExecutionContext.SessionState.Path.CurrentLocation).Provider.Name -ne "FileSystem")
        {
            Push-Location # So we can move back afterwards - hopefully seamlessly

            try
            {
                # Move to the root of the first file system available, usually C:\ but why assume.
                Set-Location -Path (Get-PSDrive -PSProvider "FileSystem" | Select-Object -ExpandProperty "Root" -First 1)
                $PoppedLocation = $True
                Remove-Variable -Name "PoppedLocation"
            }
            catch
            {
                # Revert location if this fails for some inexplicable reason (no file systems?)
                Pop-Location
            }
        }
    }

    PROCESS
    {
        forEach ($Computer in $ComputerName)
        {
            if (($Computer -like "localhost") -or ($Computer -like "127.0.0.1"))
            {
                Write-Verbose -Message "Converting localhost to hostname"
                $Computer = [Environment]::MachineName
            }
            Write-Verbose -Message "Processing '$Computer'"

            if ($Count)
            {
                $EntryCounter = 1
            }

            try
            {
                $LogRoot = $Null
                if ($Null -ne $Path)
                {
                    $JoinSplat = @{
                        Path        = "\\$Computer\"
                        ChildPath   = ($Path -replace ":", "$")
                        ErrorAction = "Stop"
                    }

                    $UNCPath = Join-Path @JoinSplat
                    if (Test-Path -Path $UNCPath -ErrorAction "Stop")
                    {
                        $LogRoot = Resolve-Path -Path $UNCPath -ErrorAction "Stop"
                    }
                }
                else
                {
                    $LogRoot = Resolve-Path "\\$Computer\C$\Windows\CCM\Logs\" -ErrorAction "Stop"
                }

                if ($LogRoot -match "^Microsoft.Powershell")
                {
                    $LogRoot = $LogRoot -Split "::" | Select-Object -Last 1
                }
            }
            catch
            {
                Write-Warning -Message "Problems were encountered resolving '$LogRoot'"
                $PSCmdlet.ThrowTerminatingError($_)
            }

            if (-not (Test-Path -Path $LogRoot))
            {
                Write-Warning -Message "Unable to resolve/access '$LogRoot'"
                Continue
            }

            Write-Verbose -Message "Testing for connectivity to '$Computer'"
            if (($Computer -eq [Environment]::MachineName) -or
                (Test-Connection -ComputerName $Computer -Quiet -Count 2))
            {
                $LogSearchSplat = $Null
                $LogSearchSplat = @{
                    Path = $LogRoot
                    File = $True
                }

                $LogFiles = $Null
                $LogFiles = if ($AllLogs)
                {
                    try
                    {
                        $LogSearchSplat.Add("Filter", "*.log")
                        Get-ChildItem @LogSearchSplat  | Select-Object -ExpandProperty "FullName"
                    }
                    catch
                    {
                        $PSCmdlet.ThrowTerminatingError($_)
                    }
                }
                else
                {
                    forEach ($Log in ($LogName | Sort-Object -Unique))
                    {
                        try
                        {
                            Write-Verbose -Message "Locating '$Log' log(s)."
                            $LogSearchSplat.Remove("Filter")
                            $LogSearchSplat.Add("Filter", "$Log*.log")
                            Get-ChildItem @LogSearchSplat  | Select-Object -ExpandProperty "FullName"

                        }
                        catch
                        {
                            Write-Warning -Message "Problems were encountered '$Log' logs from '$LogRoot'"
                            $PSCmdlet.ThrowTerminatingError($_)
                        }
                    }
                }

                Write-Verbose -Message "'$($LogFiles.Count)' logs found."
                forEach ($LogFile in $LogFiles)
                {
                    if (Test-Path -Path $LogFile -ErrorAction "Stop")
                    {
                        $CurrentLog = ((Split-Path $LogFile -Leaf) -replace '^_') -split '-' | Select-Object -First 1

                        try
                        {
                            $Parameters = @{
                                Path        = $LogFile
                                Tail        = 2000     # I'm reluctant to read the entirety of the files by default and this seems likely to read most logs.
                                ErrorAction = "Stop"
                            }

                            Write-Verbose -Message "Reading log ($LogFile)."
                            $LogContents = Get-Content @Parameters
                        }
                        catch [System.UnauthorizedAccessException]
                        {
                            Write-Warning -Message "Unable due to retrieve details to an 'Unauthorized Access' exception. Ensure you have the required permissions."
                            $PSCmdlet.ThrowTerminatingError($_)
                        }
                        catch
                        {
                            $PSCmdlet.ThrowTerminatingError($_)
                        }

                        forEach ($LogEntry in $LogContents)
                        {

                            $LogSplat = @{
                                InputObject = $LogEntry
                            }

                            if ($After)
                            {
                                $LogSplat.Add("After", $After)
                            }
                            if ($Before)
                            {
                                $LogSplat.Add("Before", $Before)
                            }

                            $ParsedEntry = Read-LogEntry @LogSplat

                            if (($Null -ne $Count) -and ($Null -ne $EntryCounter))
                            {
                                if ($EntryCounter -gt $Count)
                                {
                                    Write-Debug -Message "Count is: $EntryCounter/$Count"
                                    Break
                                }
                                else
                                {
                                    Write-Debug -Message "Incrementing counter ($EntryCounter)"
                                    $EntryCounter++
                                }
                            }

                            [PSCustomObject]@{
                                ComputerName = $Computer
                                Source       = $CurrentLog
                                Timestamp    = $ParsedEntry.TimeStamp
                                Message      = $ParsedEntry.Message
                                Path         = $LogFile
                            }
                        }
                    }
                }
            }
        }
    }

    END
    {
        if ($PoppedLocation)
        {
            Pop-Location # Revert to original location
        }
    }
}