How to output foreach into CSV using Powershell? -


i displaying users in group this:

import-module activedirectory  $groups = get-adgroup -filter {name -like "uc_*"} | select -expandproperty name   # uc_* group  foreach ($group in $groups){ write-output "group"  write-output "-----" $group write-output "" get-adgroupmember -identity $group | select -property name, samaccountname  write-output "" } 

i want output csv when do, looks each line getting overwritten next line in loop there no data in csv. not working properly:

# users in group or groups  import-module activedirectory   function get-users {     $groups = get-adgroup -filter {name -like "uc_*"} | select -expandproperty name   # uc_* group      foreach ($group in $groups){     write-output "group"      write-output "-----"     $group     write-output ""     get-adgroupmember -identity $group | select -property name, samaccountname      write-output ""     } }  get-users | export-csv "c:\temp\myfile.csv" 

how can output content csv properly?

the output of function write-output's, $group, , objects returned get-adgroupmember. collection of different objects makes not able exported export-csv, text document via out-file.

if want export csv, need create collection of consistent objects properties want export:

so we'll loop on each group foreach-object, , store group membership in $members. can loop on foreach, means can still use information foreach-object loop in $_ name of group, , user information in $member , create object every user information that's needed making [pscustomobject]

get-adgroup -filter "name -like 'uc_*'" |     foreach-object {         $members = get-adgroupmember $_         foreach ($member in $members) {             [pscustomobject]@{                 "group name"     = $_.name                 "samaccountname" = $member.samaccountname                 "user name"      = $member.name             }         }     } |     export-csv "c:\temp\myfile.csv" 

also @mklement0 mentioned, it's best practice not use scriptblock's filters on ad cmdlets. his excellent answer here gives details why.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -