VinnyGuitara
VinnyGuitara

Reputation: 605

How can I get a count from a PS command

I have a powershell command:

Get-ADGroupMember -identity "CCVGHCFinReadOnly" -Recursive | foreach{ get-aduser -properties employeeid $_} | select SamAccountName,objectclass,name,employeeid | Export-Csv "C:\Temp\AD Membership\GovReadOnly.csv

This script works great to return members of AD groups. I also want to add the count for auditing purposes. So the script should list all ad users and then a count at the bottom.

Right now if I use | Measure it gives me a count but that is all I get. So I can either get the actual users in the AD group OR the count. How can I get both with this one command?

Upvotes: 0

Views: 352

Answers (2)

Jason Boyd
Jason Boyd

Reputation: 7019

Off the top of my head side effects come to mind. In this example I am incrementing a variable outside of the pipeline from within the pipeline. I admit it feels kind of gross. Maybe somebody else can suggest a solution that does not rely on this sort of side effect.

$count = 0
Get-ADGroupMember -identity "CCVGHCFinReadOnly" -Recursive `
| foreach { 
    $count++
    get-aduser -properties employeeid $_} `
| select SamAccountName,objectclass,name,employeeid `
| Export-Csv "C:\Temp\AD Membership\GovReadOnly.csv

Now you can do whatever you want with $count.

Upvotes: 1

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200193

$members = Get-ADGroupMember ... | select SamAccountName,objectclass,name,employeeid

$members | Export-Csv "C:\Temp\AD Membership\GovReadOnly.csv"
@($members).Count | Add-Content "C:\Temp\AD Membership\GovReadOnly.csv"

Upvotes: 1

Related Questions