got a powershell script that has to use First and Last Name from CSV to do some password settings.
Import-Module ActiveDirectory
$Users = Import-Csv -Path "C:\users-to-reset.csv"
ForEach ($User in $Users) {
$LastName = $User.LastName
$FirstName = $User.FirstName
$User = Get-ADUser -Filter 'surname -eq $LastName -and givenName -eq $FirstName'
Set-ADUser -Identity $User -PasswordNeverExpires:$false
Set-ADUser -Identity $User -CannotChangePassword:$false
}
What am I doing wrong?
In the past, I have just used Set-ADAccountPassword and Set-ADUser to do this.
Set-ADAccountPassword -Identity $user -Reset -NewPassword $pw
I just used the -ChangePasswordAtLogon and -PasswordNeverExpires flags like this:
Set-ADUser -ChangePasswordAtLogon $true -Identity $($user.samAccountname) -Confirm:$false
Related
I input a list of groups for each user in CSV, and tried to create users using PowerShell code.
This is the PowerShell code:
- name: Change group for AD users
ansible.windows.win_powershell:
script: |
[CmdletBinding()]
param (
[array]
$datalist
)
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups
$users = Get-ADUser -Filter "SamAccountName -eq '$name'"
Get-ADUser -Filter "SamAccountName -eq '$name'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
Add-ADGroupMember -Identity $groups -Members $users
}
parameters:
datalist: "{{ hostvars.localhost.list }}"
I ended up getting this error:
"message": "Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. Specified method is not supported."
Also tried '$groups':
"message": "Cannot find an object with identity: '$groups' under: 'DC=adexample,DC=local'.",
And "$groups":
"message": "Cannot find an object with identity: 'CN=GroupA,OU=Groups,DC=adexample,DC=local CN=Test Group,OU=Groups,DC=adexample,DC=local' under: 'DC=adexample,DC=local'.",
This is how I input my list of groups into the CSV file:
Groups
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
What is the right way to write $groups so that my list of groups can be output correctly?
Updated with CSV in plain text:
FirstName,SamAccountName,path,UserPrincipalName,Groups
Greg,gre.b87,"OU=Temporary Users,DC=adexample,DC=local",gre.b87#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
Zee,zeef.cd,"OU=Temporary Users,DC=adexample,DC=local",zeef.cd#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
I adapted bhuvanachand komara's to mine and it worked for me:
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups -split ";"
Get-ADUser -Filter "SamAccountName -eq '$samname'"
$users = Get-ADUser -Filter "SamAccountName -eq '$samname'"
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $user
}
Get-ADUser -Filter "SamAccountName -eq '$samname'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
}
The main thing is that I need to add $groups = $user.Groups -split ";" and another foreach loop for the groups.
$csvFile = 'path\to\csv\file.csv'
$users = Import-Csv -Path $csvFile
foreach ($user in $users) {
$samAccountName = $user.SamAccountName
$givenName = $user.GivenName
$surname = $user.Surname
$password = $user.Password
$email = $user.Email
$groups = $user.Groups -split ","
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-ADUser -SamAccountName $samAccountName -GivenName $givenName -Surname $surname -DisplayName "$givenName $surname" -EmailAddress $email -AccountPassword $securePassword -Enabled $true
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $samAccountName
}
}
Example CSV
SamAccountName,GivenName,Surname,Password,Email,Groups
user1,chand,komara,Password1,user1#example.com,group1,group2
user2,bhuvan,unnava,Password2,user2#example.com,group2,group3
For each user in the $users array, the code creates a new Active Directory user using the New-ADUser cmdlet with the specified SamAccountName,
GivenName, Surname, DisplayName, EmailAddress, and account password.
It then adds the user to the specified groups using the Add-ADGroupMember cmdlet.
I have created a script for a project with some code which I was given fused with my own. Most of the commands which are great, but unfortunately two commands are not working.
These commands are:
Set-ADUser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Any ideas? I appreciate the help!
Here is the full script:
$UserName = Read-Host "Please enter username to be disabled"
if ($UserName) {
''
} Else {
'User not Found'
}
Disable-ADAccount $UserName
Get-ADUser $UserName -Properties MemberOf | ForEach-Object {
$_.MemberOf | Remove-ADGroupMember -Members $_.DistinguishedName -Confirm:$false }
$title = get-aduser $UserName -properties title
$title = $title.title
$old=Get-ADuser $UserName -properties Description
$old = $old.description
$new = "DISABLED " + $old
set-aduser $UserName -description $new
set-aduser $UserName -clear "manager"
set-aduser $UserName -clear "telephonenumber"
# these two:
set-aduser $UserName -replace #{title="Former Employee" + $title}
Move-ADObject -Identity $UserName -TargetPath "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
I think it's better to clear up a bit of your code. Have a look at this:
$SamAccountName = Read-Host 'Please enter the SamAccountName of the user you want to disable'
$VerbosePreference = 'SilentlyContinue'
$VerbosePreference = 'Continue'
Try {
$ADUser = Get-ADUser -Identity $SamAccountName -Properties MemberOf, Title, Description
Write-Verbose "User '$($ADUser.Name)' found in AD"
}
Catch {
throw "No user found in AD with SamAccountName '$SamAccountName'"
}
Write-Verbose 'Disable user'
Disable-ADAccount $ADUser
foreach ($Group in $ADUser.MemberOf) {
Write-Verbose "Remove user from group '$Group'"
Remove-ADGroupMember -Identity $Group -Members $ADUser -Confirm:$false
}
$NewTitle = "Former Employee {0}" -f $ADUser.Title
Write-Verbose "Set 'Title' to '$NewTitle'"
Set-ADUser -Identity $ADUser -Title $NewTitle
$NewDescription = "DISABLED {0}" -f $ADUser.Description
Write-Verbose "Set 'Description' to '$NewDescription'"
Set-ADUser -Identity $ADUser -Description $NewDescription
foreach ($Property in #('Manager', 'telephonenumber')) {
Write-Verbose "Clear property '$_'"
Set-ADUser -Identity $ADUser -Clear $Property
}
$NewTargetPath = "OU=Former Employee,OU=Users,OU=Contoso,DC=Contoso,DC=local"
Write-Verbose "Move AD User to '$NewTargetPath'"
Move-ADObject -Identity $ADUser -TargetPath $NewTargetPath
Some tips:
Use Write-Verbose to show what is happening in the script. Yuo can disable/enable this by commenting out the VerbosePreference.
Always start with retrieving an object instead of working with text strings ($UserName vs $ADUser). See Get-ADUser as the very first action.
Work with Try/Catch in case things fail.
Always use the parameter names. It makes it more clear on what you're trying to do.
My need is to feed attribute 'Ms-Ds-ConsistencyGUID' in our AD but It looks way more difficult than I expected. Here is the script I have done so far :
ipmo activedirectory
# Combo box
$collection = #()
$a = [System.Management.Automation.Host.ChoiceDescription]::new("&Oui")
$collection+=$a
$b = [System.Management.Automation.Host.ChoiceDescription]::new("&Non")
$collection+=$b
$annuler =
[System.Management.Automation.Host.ChoiceDescription]::new("&Annuler")
$collection+=$annuler
$prompt = $Host.UI.PromptForChoice("Messagerie","L'utilisateur aura-t-il
besoin d'une messagerie ?",$collection,0)
Switch ($prompt) {
0 {
# Import CSV file
$users = import-csv C:\Users\...\Desktop\test_bulk.csv -delimiter ";"
foreach ($User in $users)
{
# User's info
$Displayname = $User.Givenname + " " + $User.Surname
$Usersurname = $User.Surname
$Userfirstname = $User.Givenname
$SAM = $User.Samaccountname
$OU = $User.path
$password = $User.Password
$UPN = $SAM + "#...com"
$emailaddress = ($User.Givenname + "." + $User.Surname + "#...com").ToLower()
$description = get-aduser -Identity $User.gpuser -Properties Description | select -ExpandProperty description
$homedirectory = "\\server\$($User.Samaccountname)"
$infotab = $User.invcode
[guid]$obGUID = get-aduser $newuser -Properties objectguid | Select -ExpandProperty Objectguid
$newuser = New-ADUser -PassThru -Name $Displayname -Surname
$Usersurname -GivenName $Userfirstname -SamAccountName $SAM -Path $OU
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) -
Enabled $true -ChangePasswordAtLogon $false -PasswordNeverExpires $false
-UserPrincipalName $UPN -EmailAddress $emailaddress -Description
$description -ScriptPath "login.vbs" -HomeDrive "H:" -HomeDirectory
$homedirectory
-OtherAttributes #{businesscategory="Internal";
info="|MAIL_MAILBOX_O365||RU_$($infotab)|"; ms-ds-consistencyguid =
"$obguid"}
# Group membership
$gpuser = Get-ADPrincipalGroupMembership $User.gpuser | select -ExpandProperty name
$excludefromlist = #("Group1", "Group2", "Group3")
$newgrouplist = $gpuser | where {$_ -notin $excludefromlist}
# Creation of the new user
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $newgrouplist
}
}
1 { ... }
2 { ... }
}
As you can see attribute 'ms-ds-consistencyGUID' is fed with the variable '$obguid'. But that variable extracts objectGUID out of the new user's profile which is on the way to be created. This is kinda tricky.
Do you have any idea how I can set that?
You can't set the attribute at the time of creation since the GUID is not known yet. You will have to update it after you create it.
You're already specifying the PassThru parameter, which means that the New-ADUser command will return the new user, which then means you can pass that to Set-ADUser.
$newuser = New-ADUser -PassThru ...
Set-ADUser $newuser -Replace #{"ms-ds-consistencyGUID" = $newuser.ObjectGUID}
#Gabriel, You mean I can state these two cmdlets without any issue :
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $newgrouplist
Set-ADUser $newuser -Replace #{"ms-ds-consistencyGUID" = $newuser.ObjectGUID}
I thought it was not the right way to go but it finally works so...
I am creating a script that will help my colleagues to create a new AD user. This is what I have done so far:
ipmo activedirectory
$users = import-csv C:\Users\...\Desktop\test_bulk.csv -delimiter ";"
foreach ($User in $users)
{
$Displayname = $User.Givenname + " " + $User.Surname
$Usersurname = $User.Surname
$Userfirstname = $User.Givenname
$SAM = $User.Samaccountname
$OU = $User.path
$password = $User.Password
$newuser = New-ADUser -PassThru -Name $Displayname -SamAccountName $SAM -
GivenName $Userfirstname -Surname $Usersurname -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force)-Enabled $true -Path $OU -ChangePasswordAtLogon $false -PasswordNeverExpires $true -OtherAttributes #{businesscategory="Internal"}
$gpuser = Get-ADPrincipalGroupMembership $User.gpuser | select -ExpandProperty name
Add-ADPrincipalGroupMembership -Identity $newuser -MemberOf $gpuser
}
As you can see I have set a variable $gpuser so I can output a user's group membership to set all these into the new user's membership.
But there is a little hurdle... I need to remove up to three groups from the retrieved list.
I mean each time I output a user's membership I need to remove a few groups IF they are present in the list.
The thing is I don't know how to script that and where to start.
You should take a look at the Where-Object cmdlet and the -notin operator.
Basically you will do something like this:
$excludeFromThisList = #("group1", "group2")
$newGroupList = $gpuser | Where-Object { $_ -notin $excludeFromThisList }
I have code to import users and modify their properties:
Import-Csv users.csv |
select Surname, #{n='GivenName';e={$_.'FirstName'}},
#{n='samaccountname';e={$_.FirstName.substring(0,2) + $_.Surname}},
#{n='UserPrincipalName';e={$_.FirstName.substring(0,2) + $_.Surname}},
#{n='Name';e={$_.'FirstName' + ' ' + $_.'Surname'}} |
New-ADUser -Enabled $true -AccountPassword (ConvertTo-SecureString -AsPlainText "Password1" -Force) -ChangePasswordAtLogon $true -Path "OU=Intake 20XX,OU=Students,OU=Ravenloft users,DC=RAVENLOFT,DC=test" -ProfilePath {"\\TESTSVR\Profiles$\Intake20XX\" +$_.SamAccountName} -HomeDrive "D:" -HomeDirectory {"\\TESTSVR\Work$\Intake20XX\" +$_.SamAccountName} -PassThru |
Foreach-Object {
Add-ADGroupMember -Identity "CN=StudentGroup,OU=Students,OU=Ravenloft users,DC=RAVENLOFT,DC=test" -Members $_
}
What I'm looking to do is add them to a second group in addition to the "Studentgroup" that is already working.
Simply do another Add-ADGroupMember:
Foreach-Object {
Add-ADGroupMember -Identity 'StudentGroup' -Members $_
Add-ADGroupMember -Identity 'othergroup' -Members $_
}
You can use the SamAccountName of the groups, BTW. The distinguished name is not required.
With that said, if you want to add all new users to the same group, it would be better to collect the users in a variable, and then add them all in one go:
$users = Import-Csv users.csv | ... | New-ADUser ... -PassThru
Add-ADGroupMember -Identity 'StudentGroup' -Members $users
Add-ADGroupMember -Identity 'othergroup' -Members $users