add exported data from console to csv file - powershell

I have script to export users and groups name from active directory to powershell console. Data is exported and it is ok, but Now, I need to add them from console to csv file with columns: Group Name and Users.
Please check below code:
$groups = "first_group","second_group"
ForEach ($Group in $Groups) {
Get-ADGroupMember -identity $group |
Get-ADUser -properties displayName |
Select-Object SamAccountName, displayName, #{name="group";expression={$group}}
}
Please assist to solve it.

**try this **
$groups = "first_group","second_group"
$Table = #()
$Record = #{
"Group Name" = ""
"Name" = ""
"Username" = ""
}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name, samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table
$Table | export-csv "C:\Temp\Group.csv" -NoTypeInformation
`
this is the update for distinguishedname
$Record = #{
"Group Name" = ""
"Name" = ""
"Username" = ""
"Group distinguishedName"=""
}
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | select name, samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group
$Record."Group distinguishedName" = (Get-ADGroup -Identity $group).DistinguishedName
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}

Related

Counting member PER Active Directory Group using Powershell

Good Morning World
I have written the below Powershell Script which gives me almost what I want.
The error is that this script gives me an incorrect value for the total of members (users).
The incorrect value of members is always 0 (zero).
I need to the number of members (users) PER group.
I welcome your help.
$Groups = (Get-AdGroup -filter 'Name -notlike "Domain Computers"' | select name -expandproperty name)
$Table = #()
$Record = [ordered]#{
"Group Name" = ""
"Name" = ""
"Username" = ""
"Membercount" = 0
}
Foreach ($Group in $Groups)
{
$Arrayofmembers = Get-ADGroupMember -identity $Group | select name,samaccountname
foreach ($Member in $Arrayofmembers)
{
$Record."Group Name" = $Group
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$Record."Membercount" = $Membercount.count
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv C:\MB\GROUP-D.CSV -NoTypeInformation
$Arrayofmembers.Count is the correct parameter. Thanks to
Santiago Squarzon

How to use <New-Object -TypeName psobject -Property> to gather info on 2 foreach

I need to aggregate the results of 2 foreach so I can run a nice report - this is the script:
$users = Get-ADGroupMember -Identity 'TESTGRoup'
$result1 = ForEach ($user in $users){
New-Object -TypeName psobject -Property #{
User = $user
CN = $User.SamAccountName
Domain = $user.name
Name = $user.SID
}
}
$Result4 = Get-ADGroupMember 'TESTGRoup' |
Where-Object {$_.objectClass -eq 'User'} |
Get-AdUser |
ForEach {
Get-MsolUser -UserPrincipalName $_.UserPrincipalName | Select UserprincipalName, Blockcredential
$result7 = New-Object -TypeName psobject -Property #{
User1 = $Result4.UserPrincipalName
CN1 = $Result4.BlockCredential
}
}
The end result is all the users joined up on a single line and not on a table.
Sorry for the code format - not sure how to present it better.
Thanks
If I understand your question correctly, the below code will generate objects with the aggregated data you need on a single object per user:
#requires -Version 3
$results = foreach ($user in Get-ADGroupMember -Identity 'TESTGRoup')
{
$user | ? objectClass -eq User | Get-ADUser | % {
$msol = Get-MsolUser -UserPrincipalName $PSItem.UserPrincipalName
[pscustomobject]#{
'User' = $user
'CN' = $user.SamAccountName
'Domain' = $user.Name
'Name' = $user.SID
'User1' = $msol.UserPrincipalName
'CN1' = $msol.BlockCredential
}
}
}

Export AD groups, usernames and full names to csv

i'm trying to retrieve all groups, userID and names from AD and export this to CSV file with three columns, one for ParentGroupNames, then DisplayName, then memberName. The below works accept for DisplayName which seems to repeat one name for all groups.
function getGroups{
$Groups += Get-ADGroup -Filter * -SearchBase "ou=Groups,ou=DCM,ou=NTG,dc=prod,dc=main,dc=ntgov" | Select-Object -ExpandProperty samaccountname
return $Groups
}
$Groups = getGroups
write-host "Groups:" $Groups.Count
$date = $(get-date).ToString("dd MMM yyyy")
$global:FileName = "Active Directory Group Membership - DCM -" + $date
$results = #();
foreach ($GroupName in $Groups){
Get-ADGroupMember -Identity $GroupName | Sort-Object $_.SamAccountName |
ForEach-Object {
$ItemProperties = #{
"ParentGroupName" = (Get-ADGroup -Identity $GroupName).SamAccountName;
"MemberName" = $_.SamAccountName
}
if ($_.ObjectClass -eq 'group') {
$ItemProperties.Add("DisplayName","-");
} elseif ($_.ObjectClass -eq 'user') {
$ItemProperties.Add("DisplayName",(Get-ADUser -Identity $MemberName -Properties DisplayName).DisplayName);
}
$MyItem = New-Object -TypeName psobject -property $ItemProperties;
$Results += $MyItem;
$ItemProperties = $null;
}
}
$results | export-csv -path "C:
There an error in your code, change $MemberName to $ItemProperties.MemberName here's fixed code:
function getGroups{
$Groups += Get-ADGroup -Filter * -SearchBase "ou=Groups,ou=DCM,ou=NTG,dc=prod,dc=main,dc=ntgov" | Select-Object -ExpandProperty samaccountname
return $Groups
}
$Groups = getGroups
write-host "Groups:" $Groups.Count
$date = $(get-date).ToString("dd MMM yyyy")
$global:FileName = "Active Directory Group Membership - DCM -" + $date
$results = #();
foreach ($GroupName in $Groups){
Get-ADGroupMember -Identity $GroupName | Sort-Object $_.SamAccountName |
ForEach-Object {
$ItemProperties = #{
"ParentGroupName" = (Get-ADGroup -Identity $GroupName).SamAccountName;
"MemberName" = $_.SamAccountName
}
if ($_.ObjectClass -eq 'group') {
$ItemProperties.Add("DisplayName","-");
} elseif ($_.ObjectClass -eq 'user') {
$ItemProperties.Add("DisplayName",(Get-ADUser -Identity $ItemProperties.MemberName -Properties DisplayName).DisplayName);
}
$MyItem = New-Object -TypeName psobject -property $ItemProperties;
$Results += $MyItem;
$ItemProperties = $null;
}
}
$results | export-csv -path "C:\1"

Get security groups members Domain\Username

I have script that get all members of security groups across domains and export to CSV file in this format: Name, username, security group. But I want to add another row for the domain so format will look like this: domain\username, name, security group.
I could get the DN but I am only interested in just domain\username. I search around in the internet and I couldn't find anything and I am not sure if this even possible
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() $DomainList = #($objForest.Domains | Select-Object Name) $Domains = $DomainList | foreach {$_.Name}
$Groups = Import-Csv C:\ad.csv
$Table = #()
$Record = #{ "Group Name" = "" "Name" = "" "Username" = "" }
Foreach ($Group in $Groups) {
$Arrayofmembers = Get-ADGroupMember -identity $Group.groupad
-recursive -Server $Domain | select name,samaccountname
foreach ($Member in $Arrayofmembers) {
$Record."Group Name" = $Group.ad
$Record."Name" = $Member.name
$Record."UserName" = $Member.samaccountname
$objRecord = New-Object PSObject -property $Record
$Table += $objrecord
}
}
$Table | export-csv "C:\SecurityGroups3.csv" -NoTypeInformation
As Bum mentioned, you can use a regex to get the DC and combine it with the username:
$username = 'Michael'
$distinguishedName = 'CN=Domain Admins,CN=Users,DC=Fabrikam,DC=com'
$dc = [regex]::Match($distinguishedName, 'DC=([^,|$]+)').Groups[1].Value
$domainuser = '{0}\{1}' -f $dc, $username
Output of $domainuser:
$domainuser
Fabrikam\Michael

PowerShell: Get all groups a member belongs to, include group type

I have a script that gives me all members of a group with certain desired information. I want this same format but for all groups that a specified username belongs to. I want information about each group, such as group type (ie security, distribution list). How would I do this? I want a different row for each group, with information about each group in the columns.
Add-PSSnapin Quest.ActiveRoles.ADManagement
$myCol = #()
ForEach ($Group in (Get-QADGroup "CN=research,OU=Security,OU=Groups,DC=xxx,DC=com" -GroupType Security))
{
ForEach ($Member in (Get-QADGroupMember $Group -SizeLimit 0))
{
$myObj = "" | Select Group, Type, Member, Email, Username, Department
$myObj.Group = $Group.Name
$myObj.Type = $Group.groupType
$myObj.Member = $Member.Name
$myObj.Email = $Member.Email
$myObj.Department = $Member.Department
$myObj.Username = $Member.sAMAccountName
$myCol += $myObj
}
}
$myCol | Export-Csv -Path "C:\Users\sdevito\Desktop\test.csv" -NoTypeInformation
or. there is this code that i found that does something similar, but each group is in the same row, different column. i cannot figure out how to edit this code to make each group on a new row.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser sdevito -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File C:\Users\sdevito\Desktop\testt.csv
How about something like:
#Requires -Version 3.0
Add-PSSnapin Quest.ActiveRoles.ADManagement
function Get-UsersGroups {
[cmdletbinding()]
param (
[Parameter(Position=0,Mandatory)][string]$Identity,
[Parameter(Position=1)][ValidateSet('all','nested','normal')][string]$MemberType
)
$user = Get-QADUser -Identity $Identity
switch ( $MemberType ) {
'all' { $groups = $user.AllMemberOf }
'nested' { $groups = $user.NestedMemberOf }
default { $groups = $user.MemberOf }
}
foreach ( $group in $groups ) {
$groupinfo = Get-QADGroup -Identity $group
$props = [ordered]#{
Group = $groupinfo.Name
Type = $groupinfo.GroupType
Member = $user.Name
Email = $user.Email
Department = $user.Department
Username = $user.sAMAccountName
}
$obj = New-Object -TypeName PSObject -Property $props
$obj
}
}
Get-UsersGroups -Identity bob | Export-Csv -Path "C:\Users\sdevito\Desktop\test.csv" -NoTypeInformation