简体   繁体   中英

“Export-csv” in powershell

I have obtained this script to get pre-defined user from CSV then check if any user' member of' some DLs.

The script works as expected, however I need your support to add Export-Csv in it.

can you?

$userlist = Get-Content "C:\temp\users_Sam account names.csv"

foreach ($username in $userlist) {
   $grplist = (Get-ADUser $username –Properties SamAccountName, MemberOf).MemberOf | ? {$_ -like "CN=DL name*"}
    foreach ($group in $grplist) {
      select  (Get-ADGroup $group).name , (Get-ADUser $username –Properties displayname).displayname, (Get-ADUser $username –Properties mail).mail , (Get-ADUser $username ).SamAccountName  
    }
   
} 

Let's start by limiting the number of queries to AD to 1 per user and then use Select-Object to "glue" the user information from the previous query onto each group:

$userlist = Get-Content "C:\temp\users_Sam account names.csv"

# Assign all output from inside the loop to the variable `$groups`
$groups = foreach ($username in $userlist) {
   # Query AD once and save the result to a variable
   $userObject = Get-ADUser $username –Properties samAccountName,memberOf,mail
   $grplist = $userObject.MemberOf | ? {$_ -like "CN=DL name*"}
    foreach ($group in $grplist) {
      # Query AD for group name, then use calculated properties to combine with data from the `$userObject` query
      Get-ADGroup $group |Select Name,@{Name='DisplayName';Expression={$userObject.displayname}}, @{Name='Email';Expression={$userObject.mail}}, @{Name='UserName';Expression={$userObject.samAccountName}} 
    }
}

Now that all the output gets saved to $groups , exporting to CSV becomes as easy as adding the following line at the bottom:

$groups |Export-Csv -Path C:\path\to\groupMemberships.csv -NoTypeInformation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM