Am I doing something wrong with my PowerShell array? - powershell

I'm trying to prepend any groups the user is a member of with "MW-" (that is working). But when I try to do a loop to add another user to those group names with the "MW-" that I stored in $var I get an error
Cannot bind parameter 'Identity'. Cannot convert value "#{MW-" + $_.name=MW-DFS-share1}" to value of type "Selected.Microsoft.ActiveDirectory.Management.ADGroup"
$var = Get-ADUser -Identity TestUser -Properties memberof |
Select-Object -ExpandProperty memberof |
Where {$_ -match "CN=DFS*"} |
Get-ADGroup -Properties name |
Select-Object {"MW-"+ $_.name}
foreach ($group in $var) {
Add-ADGroupMember -Identity $group -Member TestUser
}
Note; When I run the Get-ADUser command it produces the output below:
"MW-"+ $_.name
--------------
MW-DFS-share1
MW-DFS-files
MW-DFS-archive

A calculated property is the easiest way to fix your issue. Then you need to either expand that property or access the property directly in your loop.
$var = Get-ADUser -Identity TestUser -Properties memberof |
Select-Object -ExpandProperty memberof |
Where {$_ -match "CN=DFS*"} |
Get-ADGroup -Properties name |
Select-Object #{Label='Name';Expression={"MW-"+ $_.name}}
foreach ($group in $var.Name) {
Add-ADGroupMember -Identity $group -Member TestUser
}
The issues with your attempt was that you never provided a property name but rather just did the calculation. In the loop, you needed to access just the calculated values rather than the object that contained a property with the values.
If the goal is to read a user list from a file and then update each user's membership, you may do the following:
foreach ($user in (Get-Content c:\userlist.txt)) {
$var = Get-ADUser -Identity $user -Properties memberof |
Select-Object -ExpandProperty memberof |
Where {$_ -match "CN=DFS*"} |
Get-ADGroup -Properties name |
Select-Object #{Label='Name';Expression={"MW-"+ $_.name}}
Add-ADPrincipalGroupMembership -Identity $user -MemberOf $var.Name
}
Using a foreach loop allows for assigning each user to a variable as you iterate through the list. That variable can then be referenced at any point within the loop.

Related

How to get-adgroup members by their Name or SamAccountName

i would like to extract members from an AD Group that contains Members and security group.
Example, Group_A:
User1
User2
User3
Group_B
When I run my script, it shows:
CN=User1,OU=Users,DC=Contoso,DC=com
CN=User2,OU=Users,DC=Contoso,DC=com
CN=User3,OU=Users,DC=Contoso,DC=com
CN=Group_B,OU=Users,DC=Contoso,DC=com
Is there another way to show their Name and/or SamAccountname?
$Groups =
#"
GroupNames;
Group_A
"# | ConvertFrom-Csv -Delimiter ';'
$ADGroups =
Foreach ($Group in $Groups){
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members }
$ADGroups.Members
As the other helpful answers show, if you want to play safe, you can use Get-ADGroupMember to get the group membership, this would also be useful because you would be able to distinguish the ObjectClass of each member.
You could also do string manipulation over the elements (distinguishedName) of the member attribute of the AD Group by following this Q&A.
If the members of the group are on different Domains, this should work however it would be quite slow most likely.
foreach($group in $groups) {
$membership = Get-ADGroup $Group -Properties Member
$membership.Member | Group-Object { ($_ -split '(?=DC=)',2)[1] } |
ForEach-Object {
[adsi]$ldap = 'LDAP://{0}' -f $_.Name
[string]$domain = $ldap.Name
foreach($member in $_.Group) {
$obj = Get-ADObject $member -Server $domain
[pscustomobject]#{
MemberOf = $membership.Name
Domain = $domain
SamAccountName = $obj.SamAccountName
ObjectClass = $obj.ObjectClass
}
}
}
}
Get-ADGroupMember has two parameters you can use for that. samaccountname, and name.
Simply do the following:
Get-ADGroupMember -identity $ADGroup | select-object SamAccountName, Name
Or in your code snippet:
Foreach ($group in $groups) {
Get-AdGroup -identity $group | select-object Samaccountname, Name }
Of course you could add:
Get-AdGroup -identity $group | select-object Samaccountname, Name | export-csv C:\mypath\report.csv
You could run a query against the returned values using Get-ADObject since it accepts DistinguishedNames as a value and isn't limited by object class:
foreach ($Group in $Groups)
{
(Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members |
ForEach-Object -Process {
Get-ADObject -Identity $_ -Properties DisplayName | Select-Object -Property DisplayName
}
}
...or, you can split the results at the desired entry:
foreach ($Group in $Groups)
{
(Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members).Members |
ForEach-Object -Process {
$_.Split(',',2).Split("=")[1]
}
}
Disclaimer: I don't have the AD Module installed on my system so I can't confirm if this is all that is needed.
The easiest way would be to expand the members property and in Get-ADGroup and then pipe it to Get-ADUser
$adUsers = Foreach ($Group in $Groups) {
Get-ADGroup $Group.GroupNames -Server contoso.com -Properties Members | Select-Object -ExpandProperty Members | Get-aduser
}

Is there a way in powershell to select what info needs to be the header so i can construct it to a table

I want to have a script that i can start and it gives me all the groups starting with APS- and its members
I want to get a HTML where it says in the Header : the group and in the table the Users
this is the code i got so far :
$properties = 'GivenName', 'Surname', 'UserPrincipalName'
Get-ADGroup -Filter {name -like "APS-*"} | ForEach {
$groupName = $_.Name
Get-ADGroupMember -Identity $_.SamAccountName |Get-ADUser -Property $properties |Select
#{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'}
But this give me a list of group,givenname,Surename,userprincipal
i want to get :
Organized like this
Is there a way of getting this ?
please consider the following points in order to accomplish the needed result
the variable $properties contains common values, you do not need to pass it to `Get-ADUser to get its values
You need to specify the parameter recursive to the command Get-ADGroupMember in order to get all child users within child groups.
If you need to output the result in HTML format you can use the command ConvertTo-Html
I modified your code to output the needed format, please check it
$groups = Get-ADGroup -Filter {name -like "APS-*"}
$list = foreach ($group in $groups) {
$groupName = $group.Name
Get-ADGroupMember -Identity $group.SamAccountName -Recursive | Get-ADUser | select #{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'
}
$out = $list | Group-Object GroupName
[string]$out_html = foreach ($item in $out){
$item.group | Select-Object 'GivenName', 'Surname', 'UserPrincipalName' | ConvertTo-Html -PreContent "<br>$($item.Name)<br><br>"
}
$out_html| Out-File .\groups.html
if you need to exclude specific users from the report, you can filter the output of Get-ADGroupMember using the Where clause as follow
# i.e. to exclude specific samaccountnames
$execlusionList = #("SamAccountName1","SamAccountName2")
Get-ADGroupMember -Identity $group.SamAccountName -Recursive | where {$_.samaccountname -notin $execlusionList} | Get-ADUser | select #{N='GroupName';E={$groupName}},'GivenName', 'Surname', 'UserPrincipalName'

Grabbing Specific AD Groups that a User is a Member Of

Just can't for the life of me figure this out. What I am trying to do is get a list of all the groups that a user is a member of. Then I would like to pass those along and grab the specific groups that I am looking for.
Below is what I have so far:
(Get-ADUser $user -Properties MemberOf ).MemberOf | Where-Object {$_.Name -contains 'Part of Group Name'}
This returns nothing. I have a feeling that I am not referencing the right property in my Where-Object but I am having a hard time finding what that is. I know the results of (Get-ADUser $user -Properties MemberOf ).MemberOf are:
CN=App - dyn_readuser_prod_WeblogicApps_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_prod_osb_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_prod_openshift_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_WeblogicApps_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_osb_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
CN=App - dyn_readuser_nonprod_openshift_NS,OU=Groups,OU=USCC,DC=int,DC=usc,DC=local
I just can't figure out how to reference "CN".
Try it this way:
(Get-ADUser $user -Properties memberOf).memberOf |
Where-Object { $_ -like 'CN=*Part of Group Name*,*' }
The (...).memberOf syntax in PowerShell v3 and later is functionally equivalent to piping to Select-Object -ExpandProperty memberOf, so you could also write it this way:
Get-ADUser $user -Properties memberOf |
Select-Object -ExpandProperty memberOf |
Where-Object { $_ -like 'CN=*part of group name*,*' }
(The second variation would be required in PowerShell v2 which doesn't support the (...).memberOf "syntactic sugar.")
There's a cmdlet that works well for grabbing the group membership of a user. Try the following:
Get-ADPrincipalGroupMembership -Identity $user | Select -ExpandProperty Name | Select-String -Pattern 'Part of Group Name'

powershell script to add users to group if not a member of another group

I have an issue with the following script:
get-aduser -filter * -searchbase "dc=domain,dc=global" -ResultSetSize $null | where-object {((get-aduser $_.samaccountname -properties memberof).memberof -ne "Mimecast Remote Access Exceptions")} | ForEach {add-adgroupmember -identity "Mimecast Internal Access" -member $_.samaccountname}
It is still adding all users but not filtering out users who are members of the remote access exceptions group. Any idea what I am doing wrong?
First of all, you don't need to perform Get-ADUser twice.
Then, the MemberOf user property is a collection, not a single string, so you need to use -notcontains instead of -ne
Try:
# get the DistinguishedName property of the group
$groupDN = (Get-ADGroup -Identity "Mimecast Remote Access Exceptions").DistinguishedName
Get-ADUser -Filter * -SearchBase "dc=domain,dc=global" -Properties MemberOf |
Where-Object {$_.MemberOf -notcontains $groupDN} |
ForEach-Object { Add-ADGroupMember -Identity "Mimecast Internal Access" -Members $_ }
Building on #Theo's Answer
.memberOf will return distinguished name strings. -notcontains won't work unless you change the left hand side to the DN. That might look something like:
$DN = 'CN=Mimecast Remote Access Exceptions,OU=SomeOU,DC=domain,DC=global'
Get-ADUser -Filter * -SearchBase "dc=domain,dc=global" -Properties MemberOf |
Where-Object {$_.MemberOf -notcontains $DN } |
ForEach-Object { Add-ADGroupMember -Identity $DN -Members $_ }
Obviously correct $DN for your environment etc...

Export AD users with list of specific groups

I've been trying to get an extract of AD users and select mail, name, memberof. I then need to list only specific groups from the memberof output so I end up with a list for each user than contains their name, email address and specific groups that match a certain name and not all of the groups they are a member of.
Get-ADUser username -Properties memberof | Select-Object memberof
I can't seem to find a way of doing this as I end up with either noteproperty above or an empty pipeline. Is there a way to achieve what I am trying to do?
The memberOf attribute contains a list of distinguishedName (DN) values, each corresponding to a group.
Retrieve the groups you are interested in, before you run Get-ADUser, that way you can compare the Group DN to the entry in memberOf:
$GroupDNs = Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | Select-Object -ExpandProperty DistinguishedName
Now, you can use those DN's to filter the group memberships with a calculated property, like so:
$UserInfo = foreach($username in #("bob","alice","joe")){
$User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
$User | Select-Object Name,mail,#{Label="GroupDNs";Expr = {$_.memberof | Where-Object {$Groups -contains $_}}}
}
without doing a new Get-ADGroup query for each memberof entry.
If you want a string of group names, rather than a NoteProperty containing an array of strings, you could fill the Groups into a hashtable and use that to "look up" the memberof entries using the ContainsKey() method:
$Groups = #{}
Get-ADGroup -Filter {Name -like "*finance*" -or Name -like "*creditcontrol*"} | ForEach-Object {
$Groups[$_.DistinguishedName] = $_
}
$UserInfo = foreach($username in #("bob","alice","joe")){
$User = Get-ADUser -Identity $username -Properties mail,memberOf |Select Name,mail,memberof
$User | Select-Object Name,mail,#{Label="Groups";Expr = { ($_.memberof | Where-Object {$Groups.ContainsKey($_)} | ForEach-Object { $Groups[$_].Name}) -join ";" }}
}
$UserInfo | Export-Csv C:\aduserinfo.csv -NoTypeInformation