0

I have the following code intended to take a list of user names and output a CSV report of username - GroupMembership. At the command line the output looks great as i get "name" on the left and recursive "group memberships" on the right (see pic https://i.sstatic.net/zLxUR.jpg for command line output, sorry can't post imbedded Pics yet)

I would like to have the output written to a CSV file with the same format, namely Username in one column and GroupMemberships in the second column.. Original code from: http://thesurlyadmin.com/2013/03/21/get-a-users-group-memberships/ with a few small changes.

Param (
   [Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
   [Alias("ID","Users")]
   [string[]]$User
)
Begin {
   Try { Import-Module ActiveDirectory -ErrorAction Stop }
   Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?"; Break }
}

Process {
    ForEach ($U in $User)
   {  $UN = Get-ADUser $U -Properties MemberOf
      $Groups = ForEach ($Group in ($UN.MemberOf))
      {   (Get-ADGroup $Group).Name
      }
      $Groups = $Groups | Sort
      ForEach ($Group in $Groups)
      {  New-Object PSObject -Property @{
            Name = $UN.Name
            Group = $Group
         }
      }
   }
}

I tried using this "$PSObject | Export-CSV C:\Scripts\GroupMembershipList.csv" but it only writes the first line to the CSV and nothing after that.

1 Answer 1

1

Nate,

In Powershell v3.0, the Export-CSV cmdlet introduced the -Append parameter.

Reference: http://technet.microsoft.com/en-us/library/hh849932.aspx

Not knowing the version of Powershell you are using, this may require an update on your side to make use of the new functionality.

In my own cases, I generally see the opposite issue if I forget to -Append to my CSV; I will only end up with the LAST entry as opposed to just the first.

I won't claim this to be your fix, but might be worth a shot...

Example: $PSObject | Export-CSV C:\Scripts\GroupMembershipList.csv -Append

Sign up to request clarification or add additional context in comments.

1 Comment

Jason, that did it sir, thank you very much! Tried to upvote and mark as answer but my reputation isn't high enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.