List group memberships for AD users - powershell

Using the following Powershell snippet I get the names of the group memberships for the current user:
$groups = [System.Security.Principal.WindowsIdentity]::GetCurrent().Groups
foreach($i in $groups){
$i.Translate([System.Security.Principal.NTAccount]).value
}
How can I modify this such I can supply the user account name as parameter?
Thanks,
Uwe

If you have access to the ActiveDirectory module, I'd suggest you use Get-ADUser. In case you can't use that module, you could use the System.DirectoryServices.AccountManagement assembly:
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$username = read-host -prompt "Enter a username"
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($ct, $username)
$groups = $user.GetGroups()
foreach($i in $groups){
$i.SamAccountName
}

You can download from Quest site this PSSnapin: Quest.ActiveRoles.ADManagement. (ActiveRoles Management Shell for Active Directory )
Is freeware and the you can do:
(get-qaduser username).memberof
To get the list of direct groups membership for the user 'username'

get-help is your best friend:
PS> get-help *member*
Name Category Synopsis
---- -------- --------
Export-ModuleMember Cmdlet Specifies the module members that are exported.
Add-Member Cmdlet Adds a user-defined custom member to an instance of a Windows PowerShell object.
Get-Member Cmdlet Gets the properties and methods of objects.
Add-ADGroupMember Cmdlet Adds one or more members to an Active Directory group.
Add-ADPrincipalGroupMembership Cmdlet Adds a member to one or more Active Directory groups.
Get-ADGroupMember Cmdlet Gets the members of an Active Directory group.
Get-ADPrincipalGroupMembership Cmdlet Gets the Active Directory groups that have a specified user, computer, group, or ser...
Remove-ADGroupMember Cmdlet Removes one or more members from an Active Directory group.
Remove-ADPrincipalGroupMembership Cmdlet Removes a member from one or more Active Directory groups.
so:
$username = "someusername"
get-adprincipalgroupmembership $username | select name

Related

How to run this script against another domain

I have the script below to give me the distinguished name for groups in a spreadsheet I have. The issue is, the groups are located in another domain. How do I point my script to that domain? Issue is I know I have to be logged in to that domain to run it but I cant.
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group | Select-Object distinguishedName
}
The cmdlets in the Active Directory module support passing in the value of the domain controller you are wanting to query. By default when you call Get-ADGroup (or any of the other) it will validate what domain it should query by checking the domain of your current machine.
The other option is to provide the -Server (doc) with the value of the Active Directory Domain Services you want to execute your query against.
You can also provide the -Credential parameter with a PSCredential object that contains your login for that other domain. This is required if the current login of your PowerShell session is not authorized to authenticate against that other domain.
So your example script would look something like this:
$AdDomain = "whatever.company.local"
$adCred = Get-Credential
$Groups = Get-Content -Path C:\Scripts\DistinguishedName.csv
ForEach ($Group in $Groups) {
Get-ADGroup -Identity $Group -Server $AdDomain -Credential $adCred | Select-Object distinguishedName
}

Powershell GPO Login Script checking AD resource group membership

The system I have to work with uses AD resource group membership to manage most of the permissions for users and computers. I have been asked to improve the current logon script as it currently contains some VB ADSISEARCHER calls. I started trying to do this purely in powershell but have hit a number of hurdles.
Target machines do not have the Active Directory Module installed
The users logging into the system have a restricted user accounts
The resource groups are nested so the script needs to handle this
I have tried a couple of approaches firstly the pure Powershell Cmdlet method of Get-ADGroup or Get-ADPricipalGroupMembership but these Cmdlet's require the Active Directory Module. Then I tried the .net approach with System.DirectoryServices.DirectoryEntry although this is a step away from a pure PowerShell solution at least it isn't as Legacy as the VB route. However when I try to build the object it also appears to be missing the name space.
First Attempt:
function Get-UserResourceMembership
{
[CmdletBinding()]
Param
(
# Username or Groupname to Discover Group Membership
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$User
)
Begin
{
$Groups = #(Get-ADPrincipalGroupMembership $User)
}
Process
{
foreach($ADGroup in $Groups)
{
if($ADGroup.ObjectClass -eq "Group")
{
Get-UserResourceMembership $ADGroup
}
$GrpMembership = #($ADGroup)
}
}
End
{
return ,$GrpMembership
}
}
Second Attempt:
# $rootGroup is passed in from earlier in the script
$groupname = $rootGroup.'Group Name'
$filter = ("(&(objectCategory=Group)(name=$($groupname)))")
$searcher.Filter = $filter
$searcher.SearchScope = "Subtree"
$searchResults = $searcher.FindAll().GetDirectoryEntry().memberOf |
% { (New-Object System.DirectoryServices.DirectoryEntry("LDAP://"+$_)) } |
Sort-Object Children | select #{name="Group Name";expression={$_.Name}}
foreach($resource in $searchResults)
{
if($resource.'Group Name' -match "<Groupname>")
{
$printResource += $resource
}
}
Does anyone in the community have any suggestions how to pull group membership [nested] from Active Directory from a standard users login script??? Any idea's much appreciated....
PS I can't change the way the system is designed (above my pay grade).
As for ...
• Target machines do not have the Active Directory Module installed
• The users logging into the system have a restricted user accounts
• The resource groups are nested so the script needs to handle this
Does not matter, they do not need to be installed on a client to use
them. You can use PSRemoting to proxy those using 'Implicit
Remoting'. The cmdlets are only available in the remote session.
Does not matter, as every user has read access, by default to ADDS
in Windows.
You can get to those using the cmdlets you are using and
there are even pre-built scripts in the Microsoft PowershellGallery.com
for this as well.
As for …
I have tried a couple of approaches firstly the pure Powershell Cmdlet
method of Get-ADGroup or Get-ADPricipalGroupMembership but these
Cmdlet's require the Active Directory Module.
As noted above, this can be addressed as described below:
PowerShell Implicit Remoting: Never Install a Module Again
Remote Session
# create a session then import a module via the session, for example:
$adsess = New-PSSession -ComputerName savdaldc01
Import-Module -Name ActiveDirectory -PSSession $adsess
Get-Module
Get-ADUser -Filter *
Remove-Module ActiveDirectory
# It's also possible to prefix modules loaded from remote servers to differentiate from local modules, e.g.
Import-Module -Name ActiveDirectory -PSSession $adsess -Prefix OnDC
Get-OnDCADUser -Filter * #I don't have regular Get-ADUser anymore
Remove-Module ActiveDirectory
Remove-PSSession $adsess
As for ...
Does anyone in the community have any suggestions how to pull group
membership [nested]
Get nested group membership - function
This function will recursively enumerate members of a given group
along with nesting level and parent group information. If there is a
circular membership, it will be displayed in Comment column.It accepts
input from pipeline and works well with get-adgroup. Download:
Get-ADNestedGroupMembers.ps1
As well as just doing this...
We can get group members by using the Active Directory powershell
cmlet Get-ADGroupMember. The Get-ADGroupMember cmdlet provides the
option to get all the nested group members by passing the parameter
-Recursive. This powershell script also handles circular membership (infinite loop) problem.
Function Get-ADNestedGroupMembers
{
[cmdletbinding()]
param
(
[String] $Group
)
Import-Module ActiveDirectory
($Members = Get-ADGroupMember -Identity $Group -Recursive)
}
Get-ADNestedGroupMembers "Domain Admins" | Select Name,DistinguishedName
or this way.
function Get-NestedGroupMember
{
param
(
[Parameter(Mandatory, ValueFromPipeline)]
[string]$Identity
)
process
{
Import-Module ActiveDirectory
$user = Get-ADUser -Identity $Identity
$userdn = $user.DistinguishedName
$strFilter = "(member:1.2.840.113556.1.4.1941:=$userdn)"
Get-ADGroup -LDAPFilter $strFilter -ResultPageSize 1000
}
}
All of the methods below list all groups including nested groups.
The example below would execute a gpresult command in the user's context. The gpresult outputs to an XML file within the user's local profile, which they should have full access to already. Then the XML file is read and traversed through each node until you reach the node containing the groups. The group list contains local and domain groups and is outputted directly to the console. This can easily be stored in a variable or output to a file. If you only want domain groups, that could easily be filtered from here with a Regex. It requires that the client machines are running at least Windows Vista SP1 or later.
gpresult /USER "$env:userdomain\$env:username" /X "$env:userprofile\rsop.xml"
$xml = [xml](Get-Content "$env:userprofile\rsop.xml")
$xml.Rsop.UserResults.SecurityGroup.Name."#text" # Displays the groups
Remove-Item "$env:userprofile\rsop.xml" # Removes the XML file
You could also use a potentially use Regex matching to find the group list:
$out = gpresult /R /USER $env:username
$GroupsUnfiltered = (($out | out-string) -split "-{10,}")[-1]
$Groups = ($GroupsUnfiltered.trim() -replace "(?m)^\s+","") -split "(?m)\r?\n"
$Groups
The following can also work if your group list always begins with a predictable group like Domain Users in this example:
$out = gpresult /R /USER $env:username
$GroupList = $out.where({$_ -match "domain users"},'SkipUntil').trim()
$GroupList
This code assumes that the users and machines are joined to the same domain or are at least joined to trusted domains. The second code snippet assumes every user is in the Domain Users group and the machines are natively PowerShell v4 or higher.

Script that shows every group user belongs

I have to create script which lists every group that user, specified by name belongs and shows name of specified user(only local groups and accounts). Specified username should be only argument in script. If we don't declare username, script should use name of user running script. If we declare username which isn't current in system, script shows nothing so there won't be error.
It's my first script homework, I understand how basic programing algorithms work. Unfortunately I'm not familiar with scripting in powershell. I would be very glad if someone could lend a hand and write script or show some directed tutorials.
As for …
Apparently Get-ADPrincipalGroupMembership is not the way
… that's not really a valid statement and there are several Q&A's on your use case on this very site. Basically, it's just something like this.
# Get users with base properties and their group membership, display user and group name
ForEach ($TargetUser in (Get-ADUser -Filter *))
{
"`n" + "-"*12 + " Showing group membership for " + $TargetUser.SamAccountName
Get-ADPrincipalGroupMembership -Identity $TargetUser.SamAccountName | Select Name
}
# Results
------------ Showing group membership for Administrator
Name
----
Domain Users
Administrators
...
------------ Showing group membership for Guest
Domain Guests
Guests
Update for OP
I used the cmdlet to explain what you were using.
If you are on PowerShell v5, there are already local group cmdlets for this.
Get-Command -Name *LocalUser*
# Results
CommandType Name
Cmdlet Disable-LocalUser
Cmdlet Enable-LocalUser
Cmdlet Get-LocalUser
Cmdlet New-LocalUser
Cmdlet Remove-LocalUser
Cmdlet Rename-LocalUser
Cmdlet Set-LocalUser
Get-Command -Name *LocalGroup*
# Results
CommandType Name
Cmdlet Add-LocalGroupMember
Cmdlet Get-LocalGroup
Cmdlet Get-LocalGroupMember
Cmdlet New-LocalGroup
Cmdlet Remove-LocalGroup
Cmdlet Remove-LocalGroupMember
Cmdlet Rename-LocalGroup
Cmdlet Set-LocalGroup
Then doing something like this...
Clear-Host
$LocalUserName = Read-Host -Prompt 'Enter a username'
# If no user is passed, list all
If($LocalUserName -eq '')
{
ForEach($GroupName in Get-LocalGroup)
{
Get-LocalGroupMember -Group "$($GroupName.Name)" |
Select #{n='GroupName';e={$($GroupName.Name)}},Name
}
}
Else
{
# process only the user passed
Get-LocalGroup |
%{
If(Get-LocalGroupMember -Group "$($_.Name)" -Member $LocalUserName -ErrorAction SilentlyContinue)
{
[PSCustomObject]#{
GroupName = $_.Name
Username = $LocalUserName
}
}
}
}
If you are on lower versions, the you can use the PowerShellGallery.com module, or use ADSI directly. There are lots of articles and samples for this on this site and all over the web.
Example:
LocalUserManagement 3.0
a module that performs various local user management functions
See also:
Managing Local User Accounts with PowerShell - Part 1

PowerShell Script to Automate New AD Group Membership

Can anyone share ideas for a PowerShell script that will create a new AD global security group and then populate it with all user objects that share a specific attribute?
Use the ActiveDirectory module.
$group_name = 'dudez'
New-ADGroup -Name $group_name `
-GroupCategory Security `
-GroupScope Global `
-Path "CN=Users,DC=foo,DC=local" `
-Description "Members of this group have identified as men."
$dudes = (Get-ADUser -Filter "...").DistinguishedName
Add-ADGroupMember -Identity $group_name -Members $dudes
First line creates the group. Second builds the list of users you want in the group. Third line adds the users to the group.
You should be able to modify this to suit your needs.

How to add various groups to the computers in OU?

I need to add various applications groups to the computers in an OU, that will be pushed out later. In AD, I go to OU, right click on the respective computer and click properties and then go to "member of" tab, and then add the various groups.
How can I automate these steps using PowerShell, so that it will apply these groups to all the computers in that OU?
import-module ActiveDirectory
$allComputers = #()
$ADgroup = "Computer Policy Application Group"
$theOU = [ADSI]"LDAP://OU=AnOU,DC=some,DC=test,DC=com"
foreach ($item in $theOU.psbase.Children) {
if ($item.ObjectCategory -like '*computer*') {
$allComputers += $item.Name
}
}
foreach ($pc in $allComputers) {
Add-ADGroupMember $ADgroup $pc
}
Then of course, you can add more groups, or setup an array of groups and iterate through it adding as you go... This will throw a lot of errors if the computer is already part of the group, by the way.
If you are using server2008 or newer (or have the required components installed) this is the simplest solution I have found.
$groupList=#("group1","group2","group3")
foreach ($Comp in (Get-AdComputer -server $ADServer -searchBase "OU=computers,DC=company,DC=com" -searchscope oneLevel")) {
foreach ($Group in $groupList) { Add-ADGroupMember -Identity $Group -Members $Comp -Server $ADServer }
}
Be sure to populate the $groupList variable with an array of the samaccountnames of the groups you wish to add, and to replace "OU=computers,DC=company,DC=com" with the LDAP Path to the OU containing the computers you wish to add permissions to.
Using the ActiveDirectory module, you can either user Add-ADPrincipalGroupMember or Add-ADGroupMember.
The former 'Adds a member to one or more Active Directory groups' whilst the latter 'Adds one or more members to an Active Directory group'.