Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0

Get user count and actual userdata in a csv file in Powershell


I am trying to get the user count and the actual userinformation through get-aduser but fail miserably.

    Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } | Select-object Samaccountname,surname,givenname | Where { $excludedusers -NotContains$_.Samaccountname } | format-list > 'C:\Scripts\Test\enabled_users_and count.csv'

Is the current code. I can add a .count before format-list like this:

(Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } | Select-object Samaccountname,surname,givenname | Where { $excludedusers -NotContains$_.Samaccountname }).count

But I only get the count of the users, as earlier said, I need both.

Extremely thankful for the help.


Solution

  • You need Two different things, Count don't need to be a field in the csv, you can get it by the line count of the final output

    You might need the count for the console use, anyway it's not logically right to save it in the final output. (if I understand you right)

    You can save it to a variable, then do export or count check...

    $Users = Get-ADUser -Server $test -Credential $1cred -Filter{enabled -eq $true} | 
    Where-Object { $_.DistinguishedName -notlike '*OU=.Service Accounts,*' -and $_.samaccountname -notlike '*health*' } |
    Where { $excludedusers -NotContains $_.Samaccountname }
    

    Export:

    $Users | Select-object Samaccountname,surname,givenname | 
    Export-CSV 'C:\Scripts\Test\enabled_users_and count.csv'
    

    Check Count:

    $Users.Count