Home > Blockchain >  How to replace only specific strings in PowerShell custom object?
How to replace only specific strings in PowerShell custom object?

Time:01-20

This is the base code:

 foreach ($event in Get-WinEvent -FilterHashtable @{LogName='Security';ID=5152}) {
    $xml = [xml]$event.toxml();
    $xml.event.eventdata.data | 
    foreach { $hash = @{} } { $hash[$_.name] = $_.'#text' } { [pscustomobject]$hash } |
    Where FilterOrigin -notmatch 'stealth|unknown|Query User Default' 
  }

the output is this:

enter image description here

I want to replace FilterOrigin with Firewall Display name, direction with either inbound or outbound and protocol with enter image description here

in the picture, only the direction is being applied correctly. the filter that blocked the connection shown in the script has a name but it's name not showing up.

CodePudding user response:

With the exception of and -- (and compound assignments such as =, ...) PowerShell's operator do not perform in-place updates - instead they return (output) a result.

The -replace operator is no exception, so for in-place updating you must assign the result of the operation back to the input variable:

$_.FilterOrigin = 
  $_.FilterOrigin -replace $pattern, (Get-NetFirewallRule -Name $Matches[0]).DisplayName

for Protocol, let's say I only want to replace TCP (6) and UDP (17), how should I do that?

$protocolName = @{ 6 = 'TCP'; 17 = 'UDP' }[[int] $_.Protocol]
$_.Protocol =  if (-not $protocolName) { $_.Protocol } else { $protocolName }

for Direction, %592 is for inbound and %593 is for outbound

# Conceptually clearer PowerShell (Core) 7  alternative:
#    $_.Direction = $_.Direction -eq '%592' ? 'Outbound' : 'Inbound'
$_.Direction = ('Outbound', 'Inbound')[$_.Direction -eq '%592']
  • Related