Here is my powershell code for adding test user accounts to Active directory... Problem: when $i is between 1 and 99, everything works fine... immediatelly after $i reaches 100, created accounts are disabled and error message in console telling "The password does not meet the length, complexity, or history requirement of the domain."
Any idea what's the problem?
//EDIT: no password policy is set for the domain
Thanks
Import-Module ActiveDirectory
for($i=1; $i -le 500; $i++){
$name="Name1_$i" #name
$surname="Surname1_$i" #surname
$logon="logon1$i" #logon
$plainPass='pAs5w0rd'+$i+'&G'
$password=ConvertTo-SecureString -AsPlainText -Force -String $plainPass
New-ADUser -Enabled 1 -Name $name -AccountPassword $password -DisplayName "$name $surname" -GivenName $name -UserPrincipalName $logon#testdomain.local -SamAccountName $logon -Surname $surname -Path "OU=SomeTest,DC=testdomain,DC=local"
}
So I reproduce your problem, you are under the default domain policy. And when :
name = Name1_100
surname = Surname1_100
samAccountName = Logon1100
A too big part of the name is in the password (see default passord policy on the domain called password complexity)
The samAccountName is checked in its entirety only to determine whether it is part of the password
So try
$plainPass='pAs5w0rd'+($i+1)+'&G'
It will work.
Related
I'm looking to create a simple powershell script that will import the user's first name from file, prompt to create a new password and loop on error when the password doesn't meet the password requirement based on the "ErrorVariable" if possible. If not, please advise.
# import user firstname from file
$firstname = $(Get-Content "C:\tmp\local\firstname.txt")
# prompt user for new password
$password = Read-Host "Hello, $firstname!! Please change your local admin account password. (Requirements: At least 8-characters, 1-Cap Letter, 1-Number) " -AsSecureString -Erroraction silentlycontinue -ErrorVariable PasswordError
# create new password
$password = $password
Get-LocalUser -Name "$firstname" | Set-LocalUser -Password $password -Erroraction silentlycontinue -ErrorVariable PasswordError
If ($PasswordError)
{
"Unable to update the password. The new password does not meet the length or complexity."
}
If (-Not $PasswordError)
{
"Password updated successfully!!"
See script above.........
Think you could simply use try/catch - e.g.:
try {
Set-LocalUser -Name $firstname -Password $password -Erroraction:stop
write-host "Password updated successfully!!"
}
Catch {
write-error $_
}
If the operation succeeded you will get "Password updated successfully!!", otherwise it returns the error.
I'm trying to reset passwords from a set username and password CSV. I have tried using the for-each method and it passes through all of the list rather than just one. Ideally I want it to ask for the username and then reset the password based on the username being entered.
The CSV is as follows
Daniel,Apples
Ben,Bannanas
Harry,Pears
Peter,Grapes
The code is very messy, but any input would be very much appreiciated. I've tried a few different ways and just can't get it to play ball!
Do I need to remove the For-Each element, basically I want it to ask me for a username and when I type it, it resets the password that is given for that username. As all are given a default password.
$Spreadsheet = Import-CSV "C:\Desktop\Password Reset\Passwords.csv"
$username = $User.'Username'
$password = $User.'Password'
ForEach($User in $Spreadsheet) {
$resetusername = Read-Host "Who's Password would you like to reset"
Set-ADAccountPassword $User.UserName -reset -NewPassword (Convertto-Securestring -asplaintext $($User.Password) -force)
Write-Host "Password reset to $password for $username"
}
Thank you very much in advance! :)
The idiomatic approach would be to filter the list of CSV records using Where-Object:
$Spreadsheet = Import-CSV "C:\Desktop\Password Reset\Passwords.csv" -Header Username,Password
$resetUsername = Read-Host "Who's Password would you like to reset"
$targetUser = $Spreadsheet |Where-Object Username -eq $resetUsername
if($targetUser){
Set-ADAccountPassword $targetUser.Username -Reset -NewPassword (Convertto-Securestring -AsPlainText $targetUser.Password -Force)
Write-Host "Password reset to $($targetUser.Password) for $($targetUser.Username)"
}
else {
Write-Host "User '$resetUsername' could not be found in spreadsheet!"
}
I'm pulling some user info from a .csv to create new users,
I've splatted the New User Params at the suggestion of someone here
but I'm getting this error
New-ADUser : The name provided is not a properly formed account name
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:67 char:17
+ New-ADUser $NewUserParms -ErrorAction Stop
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=System.Colle...=Cyclone,DC=com:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1315,Microsoft.ActiveDirectory.Management.Commands.NewADUser
the username variable seems to be correct as far as I know, when it outputs during running of the script its what I assume to be correct format of "firstname.lastname"
I have added trims and a section to remove spaces from usernames. to deal with multipart names such as Van der.... etc
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'path'
foreach ($User in $ADUsers) {
$firstName = $user.FirstName.Trim()
$surname = $user.Surname.Trim()
$vaildUsernameFormat = "[^a-zA-Z_.]" # identifies anything that's _not_ a-z or underscore or .
$username = "($firstName'.'$surname)" -replace $vaildUsernameFormat, '' #removes anything that isn't a-z
$DefaultPassword = 'Pa$$w0rd'
$NewUserParms = #{
'samAccountName' = $username;
'Name' = "$firstname $surname";
'DisplayName' = "$firstname $surname";
'UserPrincipalName' = "$username#domain.com";
'GivenName' = $firstname;
'Surname' = $surname;
'EmailAddress' = $User.Email;
'AccountPassword' = (ConvertTo-SecureString $DefaultPassword -AsPlainText -Force);
'Enabled' = $true;
'Path' = "OU=Users,DC=domain,DC=com";
}
write-host "$username this is username value"
#Check if the user account already exists in AD
if (Get-ADUser -F {
sAMAccountName -eq $username
}) {
#If user does exist, output a warning message
Write-Warning "A user account $username has already exist in Active Directory."
}
else {
#If a user does not exist then create a new user account
New-ADUser $NewUserParms -ErrorAction Stop
}
}
I've removed some of the user attributes just to make this a bit smaller.
here is the.csv as well in case I've messed something up there
link to .csv file on git
I think it's something simple. When you use splatting, you need to use the # symbol when feeding your hash table to the cmdlet rather than the regular $:
New-ADUser #NewUserParms -ErrorAction Stop
Some more reading About Splatting.
I have a small problem with the New-ADUser command in powershell.
I'm trying to create a bunch of users from a file, and I can't seem to do it right.
I do create the accounts, but when I try to log into them, it tells me that the "connection method used isn't authorized" (I am sorry if the message isn't exact, the system I'm using isn't in english)
I am using a straight out of the box AD installed on a Windows Server 2012 R2. Everything was left as default for the moment.
The command I'm using is :
for ($i = $BeginLoopAt; $i -le $EndLoopAt; $i++) {
$Id = $WorkSheet.cells.Item($i, 1).text
$FirstName = $WorkSheet.cells.Item($i, 2).text
$LastName = $WorkSheet.cells.Item($i, 3).text
$Country = $WorkSheet.cells.Item($i, 4).text
$Location = $WorkSheet.cells.Item($i, 5).text
$Department = $WorkSheet.cells.Item($i, 6).text
$AccountName = ($FirstName.Substring(0, 1) + $LastName).ToLower()
New-ADUser -Name "$AccountName" -EmployeeID $Id -Country $County -City $Location -Department $Department -GivenName $FirstName -Surname $LastName -Path "$UserPath" -ChangePasswordAtLogon $true -Enabled $true -accountPassword (ConvertTo-SecureString -AsPlainText "Azerty01" -Force) -passThru
Seeing the error, I believed that the error was coming from the fact that I didn't add a -AuthType, but after trying with both options from -AuthType, error wouldn't go away.
It event prints the following error if I choose -AuthType Basic
New-ADUser : The username is not provided. Specify username in ClientCredentials.
At C:\Users\Administrateur\Desktop\script.ps1:132 char:5
+ New-ADUser -Name "$AccountName" -EmployeeID $Id -Country $County -City $Loca ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Well, Basic AuthType seems to be for SSL login, which isn't what *I want
There is close to no difference between properties of users created with Powershell and users created through GUI. (None that I have seen)
But the users created through GUI can log in, while those created by powershell can't.
What did I miss?
Thanks in advance!
EDIT :
After some tests, i realized that, as a matter of fact, i couldn't log in with ANY account created after the AD was installed... Kinda failed before, I thought i created a user named User3 because other names were taken, and I tested with User2 that was there before AD installation...
Meaning, I can only log in accounts that existed before AD DS was installed, and I absolutely don't know why.
Change the line: -ChangePasswordAtLogon $true to -ChangePasswordAtLogon 0
You must specify at least a SAMAccountName (using the -SamAccountName option) before you can login since this is the pre-windows2000 login name which is used in a lot of places in AD (it's also used in some default environment variables of users like %username%).
See https://technet.microsoft.com/en-us/library/ee617253.aspx for the documentation on New-ADUser.
Below is my Powershell script -
Import-Module ActiveDirectory
$objOU=[ADSI]“LDAP://OU=Service,OU=Accounts,DC=xyz,DC=com”;
$dataSource=import-csv “add_user2.csv”;
foreach($dataRecord in $datasource)
{
$cn=$dataRecord.FirstName + ” ” + $dataRecord.LastName
$sAMAccountName=$dataRecord.FirstName + “.” + $dataRecord.LastName
$givenName=$dataRecord.FirstName
$sn=$dataRecord.LastName
$displayName=$sn + “, ” + $givenName
$userPrincipalName=$sAMAccountName + “#test.com”;
#Additional Attributes
$objUser=$objOU.Create(“user”,”CN=”+$cn)
$objUser.Put(“sAMAccountName”,$sAMAccountName)
$objUser.Put(“userPrincipalName”,$userPrincipalName)
$objUser.Put(“displayName”,$displayName)
$objUser.Put(“givenName”,$givenName)
$objUser.Put(“sn”,$sn)
#Place the additional attributes into the record
$objUser.Put("PasswordNeverExpires", $true)
$objUser.SetInfo()
}
I am trying to set the values of an ActiveDirectory user, using the above script. The problem I am facing is I am not able set the "PasswordNeverExpires" attribute under Account Options in Account tab to True.
My input file "add_user1.csv" looks like -
FirstName LastName
Test Account1
Will appreciate all help.
Regards.
Another thing you could use to get around having to fiddle with the UserAccountControl property is to use the PasswordNeverExpires parameter of Set-ADUser.
$objUser | Set-ADUser -PasswordNeverExpires
In fact, you could replace a lot of that code by using New-ADUser
Import-Module ActiveDirectory
$dataSource=import-csv “add_user2.csv”;
foreach($dataRecord in $datasource)
{
$cn=$dataRecord.FirstName + ” ” + $dataRecord.LastName
$sAMAccountName=$dataRecord.FirstName + “.” + $dataRecord.LastName
$givenName=$dataRecord.FirstName
$sn=$dataRecord.LastName
$displayName=$sn + “, ” + $givenName
$userPrincipalName=$sAMAccountName + “#test.com”;
New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName `
-Surname $sn -DisplayName $displayName -UserPrincipalName $userPrincipalName `
-PasswordNeverExpires $true -Path "OU=Service,OU=Accounts,DC=rjfdev,DC=com"
}
There is no PasswordNeverExpires property. If you run Get-Member on $objUser you will see this. These properties are controlled by UserAccountControl. For more information look here.
This blog article details how to set the password never expires attribute to true:
Setting "Password never expire" attribute on user object
This property unlike many other properties of AD object are contained in bitmask
attribute UserAccountControl
(not related in any way with User Account Control feature of Windows).
To set it you need to retrieve current value of this attribute and use binary OR
operation (-bor) to calculate new value.
$User = [ADSI]"LDAP://cn=Gusev,ou=Users,ou=Lab,dc=contoso,dc=com"
$UAC = $User.UserAccountControl[0] -bor 65536
$User.Put("userAccountControl",$UAC)
$User.SetInfo()
Your script needs to be modified as such:
$objUser.SetInfo()
#Place the additional attributes into the record
$UAC = $objUser.UserAccountControl[0] -bor 65536
$objUser.Put("userAccountControl",$UAC)
$objUser.SetInfo()
Without running SetInfo() twice the script will throw an error.