Okay, so I am a little new to powershell and I am trying the best I can but cannot seem to get this.
The way my directory is setup is that each organization has their own "Password Reset Group" I will have a scheduled task setup that runs based on the event log entry "Directory Service Change". The script's job is to find members in the groups and reset their password back to their employeeNumber, make the user change the password at next logon and then remove the user from the group. I seem to be having issues getting the syntax correct.
Try {
$GroupDN = (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName
}
Catch {
Write-Host "Unable to locate group: $Group because ""$($Error[0])""" -ForegroundColor Red
Exit
}
ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{ If ($User.MemberOf -contains $GroupDN)
{ $password = "$($_.employeeNumber)new!" | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
Remove-ADGroupMember -Identity "$GroupDN" -Members $User
}
}
Good to see you came up with your own answer, but you can simplify this by just using ...
Get-ADPrincipalGroupMembership
# get function / cmdlet details
(Get-Command -Name Get-ADPrincipalGroupMembership ).Parameters
Get-help -Name Get-ADPrincipalGroupMembership -Full
Get-help -Name Get-ADPrincipalGroupMembership -Online
Get-help -Name Get-ADPrincipalGroupMembership -Examples
# Example 2: Get group memberships for the Administrator
Get-ADPrincipalGroupMembership -Identity Administrator
... which lists all the groups a user belongs to.
So, your adjustment could be just this...
Get-ADUser -Filter * |
ForEach{
# "`n--- Processing user $($PSItem.SamAccountName) ---`n"
If ($TargetGroup = (Get-ADPrincipalGroupMembership -Identity $PSItem.SamAccountName) -match 'Password Reset Group')
{
$password = "$($PSItem.employeeNumber)new!" |
ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $PSItem.SamAccountName -NewPassword $password -Reset
Remove-ADGroupMember -Identity $TargetGroup.SamAccountName -Members $PSItem.SameAccountName
}
}
As for …
Okay, so I am a little new to powershell
… that is all well a good, but it is prudent for you to spend the time getting ramped up on PowerShell to limit / avoid guessing, misconception, frustration, bad habits, errors, etc., that you are going to continue to encounter (even the most experienced of us do and learn from it and each other). There are tons of no cost / free resources all over the we for you to leverage.
Live on YouTube, MVA, MSDN Channel9 for all the video training.
Use tools that will write the code for you, that you can save and tweak as needed later. Especially when it comes to ADDS.
Active Directory Administrative Center: Getting Started
Active Directory Administrative Center
Step-By-Step: Utilizing PowerShell History Viewer in Windows Server 2012 R2
Free Books and references
Using the information given to me by #AdminOfThings. I was able to write the code I wanted. It took a lot of playing around but here it is:
ForEach ($GroupDN in (Get-ADGroup -Filter {Name -like '*Password Reset Group*'}).DistinguishedName)
{ ForEach ($User in (Get-ADUser -Filter * -Properties MemberOf,employeeNumber))
{ If ($User.MemberOf -contains $GroupDN)
{ $password = $User.employeeNumber | ConvertTo-SecureString -AsPlainText -Force
Set-ADAccountPassword -Identity $User -NewPassword $password -Reset
Set-ADUser -Identity $User -ChangePasswordAtLogon $true -PasswordNeverExpires $false
Remove-ADGroupMember -Identity "$GroupDN" -Members $User -Confirm:$false
}
}
}
Related
Can someone assist me in how can I search all of AD for a users, who I would not know if exist or not.
Root domain (NA1.local)
Resource Domain (domain1.local, domain2.local, domain3.local)
MSmith (not sure where in the domain he\she is located or if the userid has been deleted from AD)
$user = PSmith
foreach ($domain in $domains)
{
Get-ADUser -Identity $username -Server $domain -ErrorAction SilentlyContinue
if ($? -eq 'True') {
$forest = Get-ADUser $username -Server $domain
Add-ADGroupMember -Identity $GPName -Member $forest -Server $VbrickSrv }
}
Specify the username with the -Filter or -LDAPFilter vs. the -Identity parameter. The filters are usually faster because they do the filtering on the DC instead of locally on the machine running the script. Also, the cmdlet won't generate an exception if nothing is returned when using the filter (over the identity) parameters.
$user = Get-ADUser -Filter { SamAccountName -eq 'psmith' }
...
I normally tell you to set the search base to whatever makes sense for your search. The more restrictive the better, but I see you want to search the entire domain. Just keep that in the back of your mind.
Check the following article out for a deeper discussion.
https://social.technet.microsoft.com/wiki/contents/articles/28485.filters-with-powershell-active-directory-module-cmdlets.aspx
As well as what #Adam said about using a filter rather than a where clause (which is the proper answer) , you can simplify your code a bit when you find the user
foreach ($domain in $domains) {
If ($u = Get-ADUser -Filter 'SamAccountName -eq "psmith"' -server $domain) {
Add-ADGroupMember -Identity $GPName -Members $u -Server $domain
Break #this should exit from the foreach loop
}
}
I have a script to disable users in AD with the following steps:
asks for username
set "domain users" group as primary group
disable users in AD
move to disabled OU
clear Manager from AD
remove all groups except 'domain users'
Add disabled_mailboxes to the user
Hide account from exchande list
Now, when i try the first time it does not work. i have to run it several times like 2 3 and 4 times to work.
When i run it step by step, it work fine also from the first time
and here is the script:
$username = Read-Host -Prompt 'Enter Username'
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
Import-Module ActiveDirectory
$user = Get-ADUser -Filter {(SamAccountName -eq $username)} -Properties MemberOf
#set "domain users" group as primary group
$group = get-adgroup "Domain Users" -properties #("primaryGroupToken")
get-aduser $username | set-aduser -replace #{primaryGroupID=$group.primaryGroupToken}
#disable users in AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Disable-ADAccount -ErrorAction SilentlyContinue
#move to disabled OU
Get-ADUser -Filter {(SamAccountName -eq $username)} | Move-ADObject –TargetPath “OU=Users,OU=Disabled Objects,DC=xxxxxxx,DC=xxx,DC=XXX”
#clear Manager from AD
Get-ADUser -Filter {(SamAccountName -eq $username)} | Set-ADUser -Clear manager
#-------------------------
#remove all groups except 'domain users'
Get-ADPrincipalGroupMembership -Identity $username | % {Remove-ADPrincipalGroupMembership -Identity $username -MemberOf $_ -Confirm:$false -ErrorAction SilentlyContinue}
#code can be removed.
#$group = $user | Select-Object -ExpandProperty MemberOf
#Remove-ADGroupMember -Identity $group -Members $user.SamAccountName -Confirm:$false -ErrorAction SilentlyContinue
#-------------------------
#Add disabled_mailboxes to the user
Add-ADGroupMember -Identity 'disabled_mailboxes' -Member $User.SamAccountName -ErrorAction SilentlyContinue
#-------------------------
#Hide account from exchande list
Set-Mailbox -identity $user.SamAccountName -HiddenFromAddressListsEnabled $true -ErrorAction SilentlyContinue
Windows 2012R2, Exchange 2010
Can anyone help with that???
Thanks
Mina
Do not use Get-ADUser repeatedly in the sequential lines. Just use the existing $user variable that you've just populated with values. Most likely you are hitting an issue that Get-ADUser returns old cached value for DN right after you run Move-ADObject (this changes the DN of the user), and since all queries use DN to locate the user, you get the error. The second run has the target user already in the destination OU, so no errors arise.
I'm using the following code to try to remove & add users to ActiveDirectory groups:
import-module ActiveDirectory
$logs = "D:\logs"
$user = "TempValue"
$group = Get-ADGroup "SomeValue"
$date = (Get-Date).ToString('yyyyMMdd')
$userPrincipal = (get-aduser "$user" -server 123 -properties *).userPrincipalName
$newUser = (get-aduser -filter "userPrincipalName -like '$userPrincipal'" -server 456)
$FileSystem = New-Object -com "Scripting.FileSystemObject"
$stream = $FileSystem.CreateTextFile("$logs\changedgroups-$date.txt", $True, $True)
Remove-ADGroupMember -Identity "$group" -Member "$user" -Confirm:$false
$stream.WriteLine("Removed $user from $group")
Add-ADGroupMember -Identity $group -server 123 -Member $newUser
$stream.WriteLine("Added $newUser to $group")
Scenario: Both domains are in the same forest Domains are in separate forests. I'm on domain "123" trying to remove a user from a group in domain 123 and add a user to that same group from domain 456.
Problem: It adds the user from domain 456, but it shows the user as a Foreign Security policy and gives the message "Note that this object is just a placeholder for a user or group from a trusted external domain." Any idea why?
I've run into this limitation of add-adgroupmember as well. To get around it switch to Set-ADGroup a few examples are provided below. You can specify the DN,SID or samaccountname withing the add or remove
Set-ADGroup -Add:#{'Member'="CN=Group3,CN=Users,DC=GLOBOMANTICS,DC=COM"} -Identity:"CN=Group1,CN=Users,DC=GLOBOMANTICS,DC=COM" -Server:"DC.GLOBOMANTICS.COM"
Set-ADGroup -Identity:"CN=Group1,CN=Users,DC=GLOBOMANTICS,DC=COM" -Remove:#{'Member'="CN=Group3,CN=Users,DC=GLOBOMANTICS,DC=COM"} -Server:"DC.GLOBOMANTICS.COM"
Let's say I have an CSV sheet, first line with the usernames and the second with the emailadresses.
Example:
Username Emailadress
jhornet jhornet#mail.com
How can I import this info to the AD within a safe and nice way, maybe with a check in it?
This is what I have till now (without CSV):
Import-Module activedirectory
$company = "International"
$username = Get-Content c:\users.txt
$emailadress = Get-Content c:\mail.txt
foreach($user in $username)
{
Set-ADuser -Identity $user -Company $company
}
#second
foreach($emailadress in $username)
{
Set-ADuser -Identity $user -EmailAddress $emailadress
}
Still learning a lot with powershell, some things are just hard to understand and better to see :)
Thanks in advance!
Gr,
JPA
I'm going out on a shaky limb here because I've never used the AD commands before but it should go something like this:
Import-Module activedirectory
$company = "International"
$users = Import-Csv c:\user.csv
$users # dumps users to allow visual inspection
read-host "press Enter to continue or Ctrl+C to abort"
$users | Foreach {Set-ADUser -Identity $_.username -Company $company -whatif}
$users | Foreach {Set-ADUser -Identity $_.username -EmailAddress $_.emailaddress -whatif}
Remove the -WhatIf parameter when you think the commands are going to work correctly.
I have some existing code that I've pieced together from my google searches.
Hi All,
I spent some time googling to find the code needed and this is what I have below.
What I'm wanting to do is log the groups being removed from a user either.
a) Into a local text (.log) file
or
b) Into the users "Notes" field.
I've found code on how to do logging if I use quest addin, but cannot fathom how to make it fit WITHOUT using quest.
Doing this as a learning + work functional task to make it speedier to disable users.
Import-Module activedirectory -ErrorAction silentlycontinue
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction silentlycontinue
$username = read-host "Username"
$users= get-aduser $username
Function RemoveMemberships
{
param([string]$SAMAccountName)
$user = Get-ADUser $SAMAccountName -properties memberof
$userGroups | %{get-adgroup $_ | Remove-ADGroupMember -confirm:$false -member $SAMAccountName}
$userGroups | %{get-adgroup $_ | Remove-ADGroupMember -confirm:$false -member $SAMAccountName} $userGroups = $user.memberof
$userGroups = $null
}
$users | %{RemoveMemberships $_.SAMAccountName}
Move-ADObject $users -TargetPath "OU=Disabled Users,DC=contoso,DC=com" -PassThru | Disable-ADAccount
edit: The inclusion of the Exchange PSSnapin is for enhancing with disabling on GAL. I have code, but didn't include it in this.
A simple on-screen answer using Write-Host
$userGroups | %{Write-Host "Removing user from group $_"; get-adgroup $_ | Remove-ADGroupMember -confirm:$false -member $SAMAccountName}