Remote Desktop Services login history for specific user - powershell

I found a script here: https://serverfault.com/questions/479048/remote-desktop-services-login-history
Here is the script:
Get-Eventlog -LogName Security | where {$_.EventId -eq "4624"} | select-object #{Name="User"
;Expression={$_.ReplacementStrings[5]}} | sort-object User -unique |ogv
The goal is to search for a specific user and see when was the last time that he have login to the terminal server, and with that script, i'am unable to make it to show the date too, only the user name, I've tried to add some property after running get-member, but didn't got any success
thank you for your help

You can use the Get-WinEvent cmdlet for this like below:
$user = 'The SamAccountName of the user you want to track'
Get-WinEvent -FilterHashtable #{LogName='Security';ID=4624} -MaxEvents 100 |
Where-Object {$_.Properties[5].Value -eq $user } |
Select-Object -Property #{Name = 'UserName'; Expression = { $_.Properties[5].Value }},
#{Name = 'LogonTime'; Expression = { $_.TimeCreated }},
MachineName |
Out-GridView
# $_.Properties[5].Value --> TargetUserName
The -MaxEvents 100 is just an example. Change that value or remove the parameter alltogether if you need to
To retrieve only 3events, use the -MaxEvents parameter with value 3.
You can also select the (last) 3 events afterwards if that is what you want by appending -Last 3 to the Select-Object command.
To see what the Properties array contains for this event ID, you can do
$props = (Get-WinEvent -MaxEvents 1 -FilterHashtable #{LogName='Security';ID=4624}).Properties
for ($i = 0; $i -lt $props.Count; $i++) {
"Properties[$i].Value --> {0}" -f $props[$i].Value
}
Comparing this to what you can read in the XML-view of eventvwr.exe:
SubjectUserSid = 0
SubjectUserName = 1
SubjectDomainName = 2
SubjectLogonId = 3
TargetUserSid = 4
TargetUserName = 5
TargetDomainName = 6
TargetLogonId = 7
LogonType = 8
LogonProcessName = 9
AuthenticationPackageName = 10
WorkstationName = 11
LogonGuid = 12
TransmittedServices = 13
LmPackageName = 14
KeyLength = 15
ProcessId = 16
ProcessName = 17
IpAddress = 18
IpPort = 19
These values differ when asking for other events and are only valid for LogName='Security';ID=4624

Try this with help from https://community.spiceworks.com/topic/2067489-powershell-script-to-get-rdp-session-history
Get-WinEvent -FilterHashTable #{LogName='Security';ID=4624} | Where-Object {$_.Properties[5].Value -eq 'UserName'} | Select-Object #{n='User';e={$_.Properties[5].Value}},#{n='Logon time';e={$_.Timecreated}}
Replace 'UserName' with your desired user.

Related

How to replace Filter Origin in this PowerShell command with Windows Firewall's display name?

Get-WinEvent -FilterHashtable #{ LogName="Security"; Id=5152; } | ? { $_.Message -like "*Outbound*" -and -not($_.message -like "*ICMP*")} | select Message | ft -wrap
Found that in here, after running it, the results look like this:
filter origin has this ID which is Firewall's unique name but I want to see a more user friendly name so I can understand immediately which Firewall rule, based on its display name that I set, blocked this connection.
Update:
I want to do something like this. but it doesn't work like this and I need help fixing it. basically, I want to keep the same output format that the original script shows and only replace things like this {a42a62ec-83d9-4ab5-9d54-4dbd20cfab17} with their display name.
$data = (Get-WinEvent -FilterHashtable #{ LogName="Security"; Id=5152; } |
? { $_.Message -like "*Outbound*" -and -not($_.message -like "*ICMP*")}).message
$data -replace "(?<=Filter Origin:[^{]+){.+?}",{(Get-NetFirewallRule -Name $Matches[0]).DisplayName}
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-7.2#replacement-with-a-script-block
You can turn events into xml and access each field seperately. I don't have your exact event type.
$a = Get-WinEvent #{ LogName='Security' } -maxevents 1
$xml = [xml]$a.toxml()
$xml.event.eventdata.data
Name #text
---- -----
SubjectUserSid S-1-5-19
SubjectUserName LOCAL SERVICE
SubjectDomainName NT AUTHORITY
SubjectLogonId 0x3e5
PreviousTime 2023-01-03T14:40:58.3894712Z
NewTime 2023-01-03T14:40:58.3975397Z
ProcessId 0x59c
ProcessName C:\Windows\System32\svchost.exe
$xml.event.eventdata.data | ? name -eq processname | % '#text'
C:\Windows\System32\svchost.exe
Get-WinEvent #{ LogName='Security' } | % { $xml = [xml]$_.toxml()
$xml.event.eventdata.data | ? name -eq 'processname' | % '#text' }
Did a quick google search and saw this documentation on troubleshooting firewalls, and it points to Get-NetFireWallRule being able to get the display name from the ID. That said, you can use some handy RegEx of (?<=Filter Origin:[^{]+){.+?} to get the unique ID and query its friendly name:
Get-WinEvent -FilterHashtable #{ LogName="Security"; Id=5152; } |
? { $_.Message -like "*Outbound*" -and $_.Message -notlike "*ICMP*" } |
Select TimeCreated, #{
Name = 'Msg'
Expression = {
if ($_.Message -match ($pattern = '(?<=Filter Origin:[^{]+){.+?}'))
{
$_.Message -replace $pattern, (Get-NetFirewallRule -Name $Matches[0]).DisplayName
}
else
{
$_.Message
}
}
} | Ft -Wrap
Placing it inside an if statement allows it to leave the message alone if no match was found for patterns that may be the unique ID. See RegEx101 for more info on the pattern itself.

PowerShell Invoke Command, Script not returning some values from remote PC's

I'm new to scripting so please excuse me if my script is messy. This script pretty much does what I want it to do but for 2 fields it doesn't return the values.
If I run the commands without Invoke I get all the values I want but when I run this with the Invoke command on remote computers the OsHotFixes and CsProcessors return weird values of "Microsoft.PowerShell.Commands.HotFix" for each hotfix and "Microsoft.PowerShell.Commands.Processor" for the CsProcessors value. All other properties gave me the values I am looking for. I'm not sure why those 2 aren't returning correct values. If someone could point me in the right direction that would be awesome.
$c = Get-Content "myfilepath"
$e = "myfilepath"
$ScriptBlock = {
$ComputerInfo = Get-ComputerInfo -Property WindowsVersion, OsBuildNumber, OsHotFixes, CsModel, BiosSMBIOSBIOSVersion, WindowsProductName, CsProcessor, OsInstallDate, OsArchitecture, CsProcessors
$GPU = Get-WmiObject win32_VideoController | Select-Object "Name", "DeviceID", "DriverVersion"
$RAM = Get-CimInstance -ClassName CIM_PhysicalMemory | Select-Object "Manufacturer", "PartNumber", #{'Name'='Capacity (GB)'; 'Expression'={[math]::Truncate($_.capacity / 1GB)}}, "Speed"
$Storage = Get-WmiObject Win32_LogicalDisk | Where caption -eq "C:" | Foreach-object {write " $($_.caption) $('{0:N2}' -f ($_.Size/1gb)) GB total, $('{0:N2}' -f ($_.FreeSpace/1gb)) GB Free"}
$MyArray = #($ComputerInfo, $GPU, $RAM, $Storage)
$Properties =
#(
'WindowsVersion'
'OsBuildNumber'
'OsHotFixes'
'CsModel'
'BiosSMBIOSBIOSVersion'
'WindowsProductName'
'OsInstallDate'
'OsArchitecture'
'CsProcessors'
'Name'
'DeviceID'
'DriverVersion'
'Manufacturer'
'PartNumber'
'Capacity'
'Speed'
'Disk'
)
$MyArray | ForEach-Object {
:Inner ForEach( $Property in $Properties )
{
If($_.$Property)
{
[PSCustomObject][Ordered]#{
hostname = $env:COMPUTERNAME
WindowsVersion = $_.WindowsVersion
Build = $_.OsBuildNumber
Patches = $_.OsHotFixes
Motherboard = $_.CsModel
BiosVersion = $_.BiosSMBIOSBIOSVersion
WindowsProductName = $_.WindowsProductName
OsInstallDate = $_.OsInstallDate
OsArchitecture = $_.OsArchitecture
Processor = $_.CsProcessors
GPUName = $_.Name
DeviceID = $_.DeviceID
DriverVersion = $_.DriverVersion
RamManufacturer = $_.Manufacturer
PartNumber = $_.PartNumber
Capacity = $_.Capacity
Speed = $_.Speed
Disk = $Storage
}
Break Inner
}
}
}
}
Invoke-Command -ComputerName $c -ScriptBlock $ScriptBlock | Sort hostname | Export-Csv -append $e -NoTypeInformation
I've tried running just the lines from 4 - 8 locally and then Outputting the Array. This will show all correct values. However when this script runs with the PSCustomObject and Invoke command I don't get CsProcessors or OsHotFixes values.

Remote PowerShell, find last 5 user logins

I am attempting to view the last 5 login events on an Enterprise machine as an Admin after a security event. I do initial investigations and am trying to find a way to quickly spit out a list of potential, 'suspects'.
I have been able to generate output that lists the logfile but under account name where you would generally see \Domain\username I only get the output, "SYSTEM" or similar.
If I had recently remoted into the machine it will pull my \Domain\Username and display it no problem.
Ideally I would like to make a script that pulls the logon events from a machine on the network with a list of who logged in recently and when.
This is what I have so far:
Get-EventLog -LogName security -InstanceId 4624 -ComputerName $_Computer -Newest 5 | Export-Csv C:\Users\username\Documents\filename
this uses the far faster Get-WinEvent cmdlet & the -FilterHashtable parameter to both speed things up a tad and to add more selectors. you may want to remove some of the filters - this was written quite some time ago for another project. [grin]
#requires -RunAsAdministrator
# there REALLY otta be a way to get this list programmatically
$LogonTypeTable = [ordered]#{
'0' = 'System'
'2' = 'Interactive'
'3' = 'Network'
'4' = 'Batch'
'5' = 'Service'
'6' = 'Proxy'
'7' = 'Unlock'
'8' = 'NetworkCleartext'
'9' = 'NewCredentials'
'10' = 'RemoteInteractive'
'11' = 'CachedInteractive'
'12' = 'CachedRemoteInteractive'
'13' = 'CachedUnlock'
}
$EventLevelTable = [ordered]#{
LogAlways = 0
Critical = 1
Error = 2
Warning = 3
Informational = 4
Verbose = 5
}
$WantedLogonTypes = #(2, 3, 10, 11)
$AgeInDays = 15
$StartDate = (Get-Date).AddDays(-$AgeInDays)
$ComputerName = $env:COMPUTERNAME
$GWE_FilterHashTable = #{
Logname = 'Security'
ID = 4624
StartTime = $StartDate
#Level = 2
}
$GWE_Params = #{
FilterHashtable = $GWE_FilterHashTable
ComputerName = $ComputerName
MaxEvents = 100
}
$RawLogonEventList = Get-WinEvent #GWE_Params
$LogonEventList = foreach ($RLEL_Item in $RawLogonEventList)
{
$LogonTypeID = $RLEL_Item.Properties[8].Value
if ($LogonTypeID -in $WantedLogonTypes)
{
[PSCustomObject]#{
LogName = $RLEL_Item.LogName
TimeCreated = $RLEL_Item.TimeCreated
UserName = $RLEL_Item.Properties[5].Value
LogonTypeID = $LogonTypeID
LogonTypeName = $LogonTypeTable[$LogonTypeID.ToString()]
}
}
}
$NewestLogonPerUser = $LogonEventList |
Sort-Object -Property UserName |
Group-Object -Property UserName |
ForEach-Object {
if ($_.Count -gt 1)
{
$_.Group[0]
}
else
{
$_.Group
}
}
$NewestLogonPerUser
current output on my system ...
LogName : Security
TimeCreated : 2019-01-24 1:50:44 PM
UserName : ANONYMOUS LOGON
LogonTypeID : 3
LogonTypeName : Network
LogName : Security
TimeCreated : 2019-01-24 1:50:50 PM
UserName : [MyUserName]
LogonTypeID : 2
LogonTypeName : Interactive
I've been fiddling with this too and also decided to use the Get-WinEvent cmdlet for this, because unfortunately, using Get-EventLog the info you want is all in the .Message item and that is a localized string..
My approach is a little different than Lee_Daily's answer as I get the info from the underlying XML like this:
#logon types: https://learn.microsoft.com/en-us/windows/desktop/api/ntsecapi/ne-ntsecapi-_security_logon_type#constants
$logonTypes = 'System','Undefined','Interactive','Network','Batch','Service','Proxy','Unlock',
'NetworkCleartext','NewCredentials','RemoteInteractive','CachedInteractive',
'CachedRemoteInteractive','CachedUnlock'
$dataItems = #{
SubjectUserSid = 0
SubjectUserName = 1
SubjectDomainName = 2
SubjectLogonId = 3
TargetUserSid = 4
TargetUserName = 5
TargetDomainName = 6
TargetLogonId = 7
LogonType = 8
LogonProcessName = 9
AuthenticationPackageName = 10
WorkstationName = 11
LogonGuid = 12
TransmittedServices = 13
LmPackageName = 14
KeyLength = 15
ProcessId = 16
ProcessName = 17
IpAddress = 18
IpPort = 19
}
$result = Get-WinEvent -FilterHashtable #{LogName="Security";Id=4624} -MaxEvents 100 | ForEach-Object {
# convert the event to XML and grab the Event node
$eventXml = ([xml]$_.ToXml()).Event
# get the 'TargetDomainName' value and check it does not start with 'NT AUTHORITY'
$domain = $eventXml.EventData.Data[$dataItems['TargetDomainName']].'#text'
if ($domain -ne 'NT AUTHORITY' ) {
[PSCustomObject]#{
Domain = $domain
UserName = $eventXml.EventData.Data[$dataItems['TargetUserName']].'#text'
UserSID = $eventXml.EventData.Data[$dataItems['TargetUserSid']].'#text'
LogonType = $logonTypes[[int]$eventXml.EventData.Data[$dataItems['LogonType']].'#text']
Date = [DateTime]$eventXml.System.TimeCreated.SystemTime
Computer = $eventXml.System.Computer
}
}
}
$result | Sort-Object Date -Descending | Group-Object -Property UserName | ForEach-Object {
if ($_.Count -gt 1) { $_.Group[0] } else { $_.Group }
} | Format-Table -AutoSize
On my machine the output looks like
Domain UserName UserSID LogonType Date Computer
------ -------- ------- --------- ---- --------
MyDomain MyUserName S-1-5-21-487608883-1237982911-748711624-1000 Interactive 27-1-2019 20:36:45 MyComputer
MyDomain SomeoneElse S-1-5-21-487608883-1237982911-748765431-1013 Interactive 27-1-2019 18:36:45 MyComputer

Partial/near match for name and/or username in Active Directory / Powershell

Our users sometimes gives us misspelled names/usernames and I would like to be able to search active directory for a near match, sorting by closest (any algorithm would be fine).
For example, if I try
Get-Aduser -Filter {GivenName -like "Jack"}
I can find the user Jack, but not if I use "Jacck" or "ack"
Is there a simple way to do this?
You can calculate the Levenshtein distance between the two strings and make sure it's under a certain threshold (probably 1 or 2). There is a powershell example here:
Levenshtein distance in powershell
Examples:
Jack and Jacck have an LD of 1.
Jack and ack have an LD of 1.
Palle and Havnefoged have an LD of 8.
Interesting question and answers. But a possible simpler solution is to search by more than one attribute as I would hope most people would spell one of their names properly :)
Get-ADUser -Filter {GivenName -like "FirstName" -or SurName -Like "SecondName"}
The Soundex algorithm is designed for just this situation. Here is some PowerShell code that might help:
Get-Soundex.ps1
OK, based on the great answers that I got (thanks #boxdog and #Palle Due) I am posting a more complete one.
Major source: https://github.com/gravejester/Communary.PASM - PowerShell Approximate String Matching. Great Module for this topic.
1) FuzzyMatchScore function
source: https://github.com/gravejester/Communary.PASM/tree/master/Functions
# download functions to the temp folder
$urls =
"https://raw.githubusercontent.com/gravejester/Communary.PASM/master/Functions/Get-CommonPrefix.ps1" ,
"https://raw.githubusercontent.com/gravejester/Communary.PASM/master/Functions/Get-LevenshteinDistance.ps1" ,
"https://raw.githubusercontent.com/gravejester/Communary.PASM/master/Functions/Get-LongestCommonSubstring.ps1" ,
"https://raw.githubusercontent.com/gravejester/Communary.PASM/master/Functions/Get-FuzzyMatchScore.ps1"
$paths = $urls | %{$_.split("\/")|select -last 1| %{"$env:TEMP\$_"}}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
for($i=0;$i -lt $urls.count;$i++){
Invoke-WebRequest -Uri $urls[$i] -OutFile $paths[$i]
}
# concatenating the functions so we don't have to deal with source permissions
foreach($path in $paths){
cat $path | Add-Content "$env:TEMP\Fuzzy_score_functions.ps1"
}
# to save for later, open the temp folder with: Invoke-Item $env:TEMP
# then copy "Fuzzy_score_functions.ps1" somewhere else
# source Fuzzy_score_functions.ps1
. "$env:TEMP\Fuzzy_score_functions.ps1"
Simple test:
Get-FuzzyMatchScore "a" "abc" # 98
Create a score function:
## start function
function get_score{
param($searchQuery,$searchData,$nlist,[switch]$levd)
if($nlist -eq $null){$nlist = 10}
$scores = foreach($string in $searchData){
Try{
if($levd){
$score = Get-LevenshteinDistance $searchQuery $string }
else{
$score = Get-FuzzyMatchScore -Search $searchQuery -String $string }
Write-Output (,([PSCustomObject][Ordered] #{
Score = $score
Result = $string
}))
$I = $searchData.indexof($string)/$searchData.count*100
$I = [math]::Round($I)
Write-Progress -Activity "Search in Progress" -Status "$I% Complete:" -PercentComplete $I
}Catch{Continue}
}
if($levd) { $scores | Sort-Object Score,Result |select -First $nlist }
else {$scores | Sort-Object Score,Result -Descending |select -First $nlist }
} ## end function
Examples
get_score "Karolin" #("Kathrin","Jane","John","Cameron")
# check the difference between Fuzzy and LevenshteinDistance mode
$names = "Ferris","Cameron","Sloane","Jeanie","Edward","Tom","Katie","Grace"
"Fuzzy"; get_score "Cam" $names
"Levenshtein"; get_score "Cam" $names -levd
Test the performance on a big dataset
## donload baby-names
$url = "https://github.com/hadley/data-baby-names/raw/master/baby-names.csv"
$output = "$env:TEMP\baby-names.csv"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -Uri $url -OutFile $output
$babynames = import-csv "$env:TEMP\baby-names.csv"
$babynames.count # 258000 lines
$babynames[0..3] # year, name, percent, sex
$searchdata = $babynames.name[0..499]
$query = "Waren" # missing letter
"Fuzzy"; get_score $query $searchdata
"Levenshtein"; get_score $query $searchdata -levd
$query = "Jon" # missing letter
"Fuzzy"; get_score $query $searchdata
"Levenshtein"; get_score $query $searchdata -levd
$query = "Howie" # lookalike
"Fuzzy"; get_score $query $searchdata;
"Levenshtein"; get_score $query $searchdata -levd
Test
$query = "John"
$res = for($i=1;$i -le 10;$i++){
$searchdata = $babynames.name[0..($i*100-1)]
$meas = measure-command{$res = get_score $query $searchdata}
write-host $i
Write-Output (,([PSCustomObject][Ordered] #{
N = $i*100
MS = $meas.Milliseconds
MS_per_line = [math]::Round($meas.Milliseconds/$searchdata.Count,2)
}))
}
$res
+------+-----+-------------+
| N | MS | MS_per_line |
| - | -- | ----------- |
| 100 | 696 | 6.96 |
| 200 | 544 | 2.72 |
| 300 | 336 | 1.12 |
| 400 | 6 | 0.02 |
| 500 | 718 | 1.44 |
| 600 | 452 | 0.75 |
| 700 | 224 | 0.32 |
| 800 | 912 | 1.14 |
| 900 | 718 | 0.8 |
| 1000 | 417 | 0.42 |
+------+-----+-------------+
These times are quite crazy, if anyone understand why please comment on it.
2) Generate a table of Names from Active Directory
The best way to do this depends on the organization of the AD. Here we have many OUs, but common users will be in Users and DisabledUsers. Also Domain and DC will be different (I'm changing ours here to <domain> and <DC>).
# One way to get a List of OUs
Get-ADOrganizationalUnit -Filter * -Properties CanonicalName |
Select-Object -Property CanonicalName
then you can use Where-Object -FilterScript {} to filter per OU
# example, saving on the temp folder
Get-ADUser -f * |
Where-Object -FilterScript {
($_.DistinguishedName -match "CN=\w*,OU=DisabledUsers,DC=<domain>,DC=<DC>" -or
$_.DistinguishedName -match "CN=\w*,OU=Users,DC=<domain>,DC=<DC>") -and
$_.GivenName -ne $null #remove users without givenname, like test users
} |
select #{n="Fullname";e={$_.GivenName+" "+$_.Surname}},
GivenName,Surname,SamAccountName |
Export-CSV -Path "$env:TEMP\all_Users.csv" -NoTypeInformation
# you can open the file to inspect
Invoke-Item "$env:TEMP\all_Users.csv"
# import
$allusers = Import-Csv "$env:TEMP\all_Users.csv"
$allusers.Count # number of lines
Usage:
get_score "Jane Done" $allusers.fullname 15 # return the 15 first
get_score "jdoe" $allusers.samaccountname 15

Seeking balanced combination of fast, terse, and legible code to add up values from an array of objects

Given the following array of objects:
Email Domain Tally
----- ----- -----
email1#domainA.com domainA.com 4
email1#domainB.com domainB.com 1
email2#domainC.com domainC.com 6
email4#domainA.com domainA.com 1
I'd like to "group by" Domain and add up Tally as I go. The end result would like this:
Domain Tally
------ -----
domainA.com 5
domainB.com 1
domainC.com 6
I have something that works but I feel like it's overly complicated.
$AllTheAddresses = Get-AllTheAddresses
$DomainTally = #()
foreach ($Addy in $AllTheAddresses)
{
if ($DomainTally | Where-Object {$_.RecipientDomain -eq $Addy.RecipientDomain})
{
$DomainTally |
Where-Object {$_.RecipientDomain -eq $Addy.RecipientDomain} |
ForEach-Object {$_.Tally += $Addy.Tally }
}
else
{
$props = #{
RecipientDomain = $Addy.RecipientDomain
Tally = $Addy.Tally
}
$DomainTally += New-Object -TypeName PSObject -Property $props
}
}
In my example, I'm creating the addresses as hashtables, but PowerShell will let you refer to the keys by .Property similar to an object.
If you're truly just summing by the Domain, then it seems like you don't need anything more complicated than a HashTable to create your running total.
The basic summation:
$Tally = #{}
$AllTheAddresses | ForEach-Object {
$Tally[$_.Domain] += $_.Tally
}
Using this sample data...
$AllTheAddresses = #(
#{ Email = "email1#domainA.com"; Domain = "domainA.com"; Tally = 4 };
#{ Email = "email1#domainB.com"; Domain = "domainB.com"; Tally = 1 };
#{ Email = "email1#domainC.com"; Domain = "domainC.com"; Tally = 6 };
#{ Email = "email1#domainA.com"; Domain = "domainA.com"; Tally = 1 }
)
And you get this output:
PS> $tally
Name Value
---- -----
domainC.com 6
domainB.com 1
domainA.com 5
Here is a "PowerShellic" version, notice the piping and flow of the data.
You could of course write this as a one liner (I did originally before I posted the answer here). The 'better' part of this is using the Group-Object and Measure-Object cmdlets. Notice there are no conditionals, again because the example uses the pipeline.
$AllTheAddresses |
Group-Object -Property Domain |
ForEach-Object {
$_ |
Tee-Object -Variable Domain |
Select-Object -Expand Group |
Measure-Object -Sum Tally |
Select-Object -Expand Sum |
ForEach-Object {
New-Object -TypeName PSObject -Property #{
'Domain' = $Domain.Name
'Tally' = $_
}
} |
Select-Object Domain, Tally
}
A more terse version
$AllTheAddresses |
Group Domain |
% {
$_ |
Tee-Object -Variable Domain |
Select -Expand Group |
Measure -Sum Tally |
Select -Expand Sum |
% {
New-Object PSObject -Property #{
'Domain' = $Domain.Name
'Tally' = $_
}
} |
Select Domain, Tally
}
Group-Object is definitely the way to go.
In the interest of terseness:
Get-AllTheAddresses |Group-Object Domain |Select-Object #{N='Domain';E={$_.Name}},#{N='Tally';E={($_.Group.Tally |Measure-Object).Sum}}