I'm trying to export some group memberships all to one CSV file so I can find users who are not in our domain. Everything works great, but when all the outputs get appended I can't see what group each entry is in. Here's what I have now.
$Groups = import-csv "C:\users\USER\desktop\secgroupinput2.csv"
foreach($item in $Groups)
{
Get-ADGroupMember -Server "SERVERDC" -Identity $item.directoryname | export-csv "C:\users\USER\desktop\realexport.csv" -Append
}
How can I add a row between appends with the group name, likely from the import?
Thanks!
I did something similar in the past. Hope this code helps :
Function ADGroupMembers
{
$group = get-content C:\Pshell\PM\group.txt
$i =25
do{
if (get-QADgroup $group[$i] -Empty 0)
{write-output ''; Write-Output -inputobject "The $($group[$i]) group members :"; write-output '';
get-QADGroupMember $group[$i] -IncludeAllProperties | Format-Table -AutoSize DisplayName, Type, Office, Company, Department, Title, WhenCreated | Out-String -Width 4096;
write-output ''}
else {Write-Output -inputobject "*** Member not found in the $($group[$i]) group!"; write-output ''}
$i +=1}
while ($i -ne $group.length)
}
ADGroupMembers | out-File 'c:\Pshell\PM\groupmemberdetails.txt'
Related
Hope all is well.
Trying to see if this possible.
Task: I have list of AD group that I need find members of each group. Only get the list active users.
Issue: I wanted to see if I can put the name of the group as Column name and Group Members under each column. Not sure if this possible. So far. I was only able to use Write-Output - Group and add extra line in way to difference each group.
$data = Import-Csv -Path C:\Source\Listofusers.csv
$results = Foreach ($datauser in $data)
{
$getadgroupmember = Get-ADGroupMember -Identity $datauser.ADGroups -Recursive | ? {$_.objectclass -eq "user"}
write-output "`n"
write-output $datauser.ADGroups
write-output "-----------------------------------------------------------------"
foreach ($activeanddisabledusers in $getadgroupmember)
{
Get-ADUser -Identity $activeanddisabledusers -Properties enabled | Where-Object {$_.Enabled -eq 'true'} | Select-Object -ExpandProperty SamAccountName}
}
I am trying to gather some information on disabled user accounts that have mailboxes. I am specifically looking for just user mailboxes not shared mailboxes.
Here is what I have so far.
$Mailboxes = Get-Mailbox | where {$_.RecipientTypeDetails -eq 'UserMailbox'}
$date = get-date -f "MMddyyyy_HHmm"
$Disabled = #()
Foreach ($Mailbox in $Mailboxes) {
if((Get-ADUser -Identity $Mailbox.SamAccountName).Enabled -eq $False){
$Disabled += Get-MailboxStatistics $Mailbox.SamAccountName | Select -Property DisplayName,TotalItemSize
}
}
$Disabled | Sort DisplayName | Export-Csv -Path "%path%\DisabledADUsersWithMailbox_$date`.csv" -NoTypeInformation
Additionally what I would like to collect is the users Title, Manager, LastlogonDate all of which can be found using Get-Aduser. I am unsure how I go about collecting the information from both cmdlets and then exporting it all to csv. I have read that I may need to create a custom object. I am struggling with setting that up in this script.
Any help would be much appreciated.
Thanks
the following lines should give you what you want, can't verify it as I have no exchange running here.
$date = get-date -f "MMddyyyy_HHmm"
$Disabled = #(
Foreach ($Mailbox in $Mailboxes) {
$adUser = get-aduser -Identity $Mailbox.SamAccountName -Properties enabled,manager,title,lastlogontimestamp
If ($adUser.Enabled -eq $False){
$mailStats = Get-MailboxStatistics $Mailbox.SamAccountName
$attrsht = [ordered]#{
displayname=$mailstats.displayname
totalitemsize=$mailStats.totalitemsize
samaccountname=$aduser.samaccountname
enabled=$aduser.enabled
manager=$aduser.manager
title=$aduser.title
lastlogontimestamp=[datetime]::FromFileTime($aduser.lastlogontimestamp)
}
new-object -TypeName psobject -Property $attrsht
}
}
)
$Disabled | Sort-Object DisplayName | Export-Csv -Path "%path%\DisabledADUsersWithMailbox_$date`.csv" -NoTypeInformation
Avoid adding elements to an array by using +=. It is slow, alternatively take a look at generic array lists.
I have a fairly simple script that needs to check around 20,000 AD Groups for their membership count. That all works fine, I can take the list of groups run it through the script and for the most entries it works fine. However I was getting some errors that I couldn't figure out and hopefully someone here can point me in the right direction.
I am using the DN of the object to query AD and for around 10% it fails, but when I copy the DN from the file, paste it into a command window and run the command manually it works fine. Some more checking and it seems that when I read an offending line into my variable there is a line break in the middle for some reason.
When looking at the value of the variable I get the following:
Working Example - "CN=ABC, OU=Location, OU=Distribution Lists, DC=Domain, DC=COM"
Error Example - "CN=ABC, OU=Location, OU=Distribution
Lists, DC=Domain, DC=COM"
It seems to insert a return in-between Distribution and Lists on certain entries in the file. I have tried deleting the character in-between and replacing it with a space but I get the same result.
Could it be the length? I am still looking for a common factor but any suggestions would be great.
Thanks
Updated with requested content.
$Groups = Import-Csv C:\Temp\DLName.csv
write-host ($Groups).Count
$i=1
foreach ($Group in $Groups)
{
$GroupInfo = Get-ADGroupMembersRecursive -Groups $Group.Name
$MembersCount = ($GroupInfo | Measure-Object).Count
$MembersList = $GroupInfo | Select Name -ExcludeProperty Name
$FriendlyName = Get-ADGroup -Identity $Group.Name
$Export = $FriendlyName.Name + ", " + $MembersCount
$Export | Out-File C:\Temp\DLMembers.csv -Append
Write-host $FriendlyName "," $MembersCount
$i
$i++
}
Entry 1 and 3 work 2 doesn't, but the formatting here seems to have wrapped the entries.
Name
"CN=Company - DL Name1,OU=Country1 Distribution Lists,OU=Europe,OU=Acc,DC=Domain,DC=Domain,DC=com"
"CN=Company - DL Name2,OU=Country2 Distribution Lists,OU=Europe,OU=Acc,DC=Domain,DC=Domain,DC=com"
"CN=Company - DL Name3,OU=Country3 Distribution Lists,OU=America,OU=Acc,DC=Domain,DC=Domain,DC=com"
Top pic is the failure second pic works.
List Creation:
$SearchScope = "OU=OUName,DC=Domain,DC=Domain,DC=com"
$SearchFilter = {GroupCategory -eq 'Distribution'}
$Groups = Get-ADGroup -SearchBase $SearchScope -Filter
$SearchFilter | Sort-Object Name
foreach ($Group in $Groups)
{
$Group.DistinguishedName | Select Name -ExpandProperty Name
$Group.DistinguishedName | Out-File C:\Temp\DLName.csv -Append
}
Do not use a self-combined comma separated string and Out-File to create CSV files, because that will get you into trouble when fields happen to contain the delimiter character like in this case the comma (which will lead to mis-aligned data).
Your List Creation code should be like this:
$SearchBase = "OU=OUName,DC=Domain,DC=Domain,DC=com"
$SearchFilter = "GroupCategory -eq 'Distribution'"
Get-ADGroup -SearchBase $SearchBase -Filter $SearchFilter |
Sort-Object Name | Select-Object Name, DistinguishedName |
Export-Csv -Path 'C:\Temp\DLName.csv' -NoTypeInformation
Then you can use that csv later to do:
$Groups = Import-Csv -Path 'C:\Temp\DLName.csv'
Write-Host $Groups.Count
$result = foreach ($Group in $Groups) {
$GroupInfo = Get-ADGroupMember -Identity $Group.DistinguishedName -Recursive
# unnecessary.. $MembersCount = ($GroupInfo | Measure-Object).Count
# unused.. $MembersList = $GroupInfo.Name
# unnecessary.. $FriendlyName = Get-ADGroup -Identity $Group.Name
# output an object with the wanted properties
[PsCustomObject]#{
GroupName = $Group.Name
MemberCount = #($GroupInfo).Count # #() in case there is only one member in the group
}
}
# show on screen
$result | Format-Table -AutoSize
# output to CSV file
$result | Export-Csv -Path 'C:\Temp\DLMembers.csv' -NoTypeInformation
As you can see, I'm not using your custom function Get-ADGroupMembersRecursive because I have no idea what that outputs.. Also, there is no need for that because you can use the Get-ADGroupMember cmdlet with the -Recursive switch added
I am still learning my way around PowerShell and I'm trying to get some data out of Intermedia using their Intermedia HostPilot PowerShell tool.
First I start out by adding all the Distribution Group information to my $Groups array:
$Groups = Get-DistributionGroup
I am able to get the DisplayName and EmailAddress of those in Distribution Groups, however I can't tell which user is in which group:
for ($i=0; $i -lt $Groups.length; $i++)
{ Get-DistributionGroupMember -Identity $Groups[$i].DistinguishedName |
Select DisplayName, EmailAddress }
I found the script below online (https://www.morgantechspace.com/2015/06/powershell-export-distribution-list-members-to-csv.html) which was helpful but I still don't see the members of the group in my csv file, just a list of the distribution groups:
$Groups = Get-DistributionGroup
$Groups | ForEach-Object {
$group = $_.GUID
$members = ''
Get-DistributionGroupMember $group | ForEach-Object {
If($members) {
$members=$members + ";" + $_.GUID
} Else {
$members=$_.GUID
}
}
New-Object -TypeName PSObject -Property #{
GroupName = $group
Members = $members
}
} | Export-CSV "C:\\Distribution-Group-Members.csv" -NoTypeInformation -Encoding UTF8
Ideally I would like to have an additional column that displays the Distribution Group for each user. Something like this:
DistributionGroup DisplayName EmailAddress
accounting Rob Smith rob.smith#yahoo.com
accounting John Quincy john.quincy#yahoo.com
This is one variation I tried:
for ($i=0; $i -lt $Groups.length; $i++)
{ Get-DistributionGroupMember -Identity $Groups[$i].DistinguishedName |
Select DisplayName, EmailAddress, $Groups[$i].DisplayName }
This just gives me a heading with the name of the first distribution group, like this:
DisplayName EmailAddress Accounting
Any tips are welcome. Thanks!
I really don't know what the Intemedia HostPilot powershell commands are but in plain powershell you could go with something like that :
$DGroups = Get-ADGroup -Filter {(GroupCategory -eq "Distribution")} | select Name
Foreach ($Group in $DGroups)
{
write-host""
write-host "Members of the >>> "$Group.Name" <<< are:"
write-host "--------"
$Users = Get-ADGroupMember $Group.Name | Select samaccountname | sort Samaccountname
Foreach ($user in $users)
{
Get-ADUser -Identity $user.samaccountname -Properties * | select Name, Samaccountname, mail, displayname
}
}
I am posting it as an answer as the code in the comments is not displayed really well.
The $Result object matches the desired format example you gave and is ready to be output to the console, piped to Out-GridView, or exported to CSV.
$DGroups = Get-DistributionGroup
$Result = #()
foreach ( $DGroup in $DGroups ) {
$DGroup | Get-DistributionGroupMember | Select-Object DisplayName, EmailAddress | ForEach-Object {
$Result += [PSCustomObject]#{
DistributionGroup = $DGroup.DisplayName
DisplayName = $_.DisplayName
EmailAddress = $_.EmailAddress
}
}
}
Hope this helps.
I've been working on a script to run through a list of groups in a CSV file to see if they have any members.
Ultimately I'm looking to have the script export the results to a separate CSV file.
$groups = Get-Content 'C:\Users\me\Desktop\testGroups.csv'
foreach ($groups in $groups) {
$users = Get-ADGroupMember -Identity $groups
if (($users | Measure-Object).Count -ne 0) {Write-Output "$groups has something" | Out-File C:\Users\me\Desktop\membersTest.csv -Append}
Else {Write-Output "$groups has nothing" | Out-File C:\Users\me\Desktop\membersTest.csv -Append}
}
This returns the following:
Length
27
31
41
30
...
I've attempted to change Write-Output to Write-Host and that appears to return the correct results, but it only displays it within the CMD window obviously.
Would someone be able to assist me with the process of correcting these IF Else statements?
End result is a csv, so build an object and export it.
$groups = Get-Content 'C:\Users\me\Desktop\testGroups.csv'
$GroupMemberCount = ForEach ($group in $groups) {
[PSCustomObhect]#{
Group = $group
MemberCount = (Get-ADGroupMember -Identity $group).Count
}
}
$GroupMemberCount | Out-Gridview
$GroupMemberCount | Export-Csv 'C:\Users\c002568\Desktop\membersTest.csv' -NoTypeInformation
I had this similar script for another project which might be helpful, I've modified to match your query. If you don't have need to display output, you can ignore that.
$groups = import-csv groups.csv
$outputFile = New-Item -ItemType file testOutputCSV.CSV -Force
foreach ($group in $groups) {
[array]$users = Get-ADGroupMember -Identity $group.samaccountname
if($users.count -ne 0){
Write-Output "$($group.samaccountname) has something "
}
else {
Write-Output "$($group.samaccountname) has 0 members"
}
$group.samaccountname +","+$users.count | Out-File $outputFile -Append
}
If the intention is to highlight the groups not having any members on console, as well as CSV, you can bring this line inside IF Else block, add more columns as needed.
$group.samaccountname +","+$users.count | Out-File $outputFile -Append
If you don't need to display anything on the console, you can omit IF Else block.
If you want to update CSV only for groups having 0 members or non-zero members, you can modify accordingly.
Edit: Masked $Users to be [array] since single member groups would return ADPrincipal