Powershell Core 6.2 Cookbook
上QQ阅读APP看书,第一时间看更新

There's more...

There is much more you can do with Add-Member. Take a look at the following example, which adds data values from an event log entry to the event so that the latter can be exported easier:

# as one practical example, take the Windows event log
$oneEvent = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4624
} -MaxEvents 1

$oneEvent | Add-Member -NotePropertyName SubjectUserName -NotePropertyValue ($oneEvent.Properties[1].Value)
$oneEvent.SubjectUserName

When retrieving objects remotely or from jobs, Add-Member is an invaluable tool as well, as the following example shows:

$deserializedEvent = Start-Job { Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4624
} -MaxEvents 1 | Add-Member -MemberType ScriptProperty -Name EventXml -Value {[xml]$this.ToXml()} -PassThru } | Wait-Job | Receive-Job
$deserializedEvent.EventXml # Useful
$deserializedEvent.EventXml.Event.EventData.Data # Everything is there to use
$deserializedEvent.ToXml() # Error - this method does not exist any longer