You could also try setting a value regardless of whether there's a match or not:
Duration = if ($_ -match '(?smi).*\ssession duration was\s+([^\s]+)\s+.*') { $matches[1] } else { "Unknown Duration" }
P.S. I can't actually test it as I only have a Win10 machine, wish I could suggest something more.
-4wd
Yeah, I had a feeling that might be a problem...
But! The duration part solved itself later in the code, when I ran it through a formatting routine that returns blank if the input is not a number:
@{Name='Duration ';Expression={'{0}' -f [timespan]::fromseconds($_.Duration).ToString("d\.hh\:mm\:ss")}}
Then I ran into a variation of the same problem on the next value that your code above worked perfectly on:
Target = if ($_.Message -match '(?smi).*to resource\s\"+([^\s]+).INTERNALDOMAINNAME.com\".\s+.*') { $matches[1] }
else {
$_.Message -replace '(?smi).*network resource:\s\"+([^\s]+).LAP.com\".\s+.*','$1'
}
The output report combines two different event types (connect and disconnect) in the same column, that both needed the same (internal resource machine name) info that was worded differently in their source event messages.
So if anybody else needs it, the now working/finished report code looks like so:
$Start = (Get-Date).AddDays(-14)
$End = Get-Date ## (Get-Date).Date AutoMagically Makes it Midnight of that Date.
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-TerminalServices-Gateway/Operational';
StartTime=$Start; EndTime=$End; ID=302,303 } | %{
(new-object -Type PSObject -Property @{
TimeStamp = $_.TimeCreated
evId = $_.ID -replace '\s',''
ClientIP = $_.Message -replace '(?smi).*on client computer\s\"+([^\s]+)\",\s+.*','$1'
UserName = $_.Message -replace '(?smi).*The user\s\"+([^\s]+)\",\s+.*','$1'
Duration = $_.Message -replace '(?smi).*\ssession duration was\s+([^\s]+)\s+.*','$1'
Target = if ($_.Message -match '(?smi).*to resource\s\"+([^\s]+).LAP.com\".\s+.*') { $matches[1] }
else {
$_.Message -replace '(?smi).*network resource:\s\"+([^\s]+).INTERNALDOMAINNAME.com\".\s+.*','$1'
}
})
} | sort UserName, TimeStamp -Descending | Select `
@{Name='Event Date and Time ';Expression={'{0}' -f $_.TimeStamp}} `
, @{Name='User Location ';Expression={'{0}' -f $_.ClientIP}} `
, @{Name='Target Machine';Expression={'{0}' -f $_.Target}} `
, @{Name='Username ';Expression={'{0}' -f $_.UserName}} `
, @{N='User Action Made ';E={
switch ($_.evId) {
302 {"Connected"}
303 {"Disconnected After:"}
default {'Should be unreachable'}
}}} `
, @{Name='Duration ';Expression={'{0}' -f [timespan]::fromseconds($_.Duration).ToString("d\.hh\:mm\:ss")}} | Format-Table -AutoSize -Wrap
Thank You!