Users created with PowerShell New-ADUser can't log in - powershell

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.

Related

Powershell user creation script - leave fields blank?

I have created a powerhell that works just fine. However from yesterday untill today, I can't leave mobile field and ipPhone field "blank" by hitting enter to continue my script. It seems like I have to enter some numbers to the field for my script to work - but sometimes when we create users do do not know the mobile and ipphone in advance.
Therefor i want to ask if anyone know what to add in order to have the ability to hit enter to leave the fields blank and add the numbers at another later time?
My script:
$Mobile = Read-Host "Type mobile number (leave blank and hit enter if you do not know the mobile number yet"
$ipPhone = Read-Host "Indtast IpPhone number (leave blank and hit enter if you do not know the IpPhone number yet)"
New-ADUser `
-Mobile "$Mobile" `
-OfficePhone "$Mobile" `
-OtherAttributes #{'ipPhone' = $ipPhone} `
It works if we type in the numbers in both Mobile and ipPhone field - but we want to leave the fields blanks sometimes - and that has worked before.
This is the error when leaving the fields blanks:
New-ADUser : The server is unwilling to process the request
At line:23 char:2
+ New-ADUser `
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=Jakob Hansen...faldvarme,DC=dk:String) [New-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.NewADUser
Use splatting
# ask someone to give the mobile and ipPhone numbers. THESE CAN BE LEFT EMPTY
$Mobile = Read-Host "Type mobile number (leave blank and hit enter if you do not know the mobile number yet"
$ipPhone = Read-Host "Indtast IpPhone number (leave blank and hit enter if you do not know the IpPhone number yet)"
# Create a Hashtable and fill in all parameters of which you are ABSOLUTELY sure they have a valid content.
# Leave out the unknown parameters like $Mobile and $ipPhone from above
# below is just a demo
$userParams = #{
SamAccountName = 'HansenJ'
Name = 'Jakob Hansen'
Givenname = 'Jakob'
Surname = 'Hanses'
Title = 'Test User'
Department = 'IT'
userPrincipalName = 'jakob.hansen#faldvarme.com'
EmailAddress = 'jakob.hansen#faldvarme.com'
AccountPassword = 'SomePa$$w0rd' | ConvertTo-SecureString -AsPlainText -Force
Enabled = $true
ChangePasswordAtLogon = $false
CannotChangePassword = $false
# etc. see https://learn.microsoft.com/en-us/powershell/module/activedirectory/new-aduser
}
# Now you add items to the above $userParams Hashtable ONLY IF THEY ARE NOT EMPTY
# if they are empty, these parameters will NOT become part of the splatting Hashtable
if (![string]::IsNullOrWhiteSpace($Mobile)) {
$userParams['MobilePhone'] = $Mobile
$userParams['OfficePhone'] = $Mobile
}
if (![string]::IsNullOrWhiteSpace($ipPhone)) {
$userParams['OtherAttributes'] = #{'ipPhone' = $ipPhone}
}
# Finally create the new user
# if you are NOT a Domain Admnin, you need to append -Credential (Get-Credential -Message "Please enter Admin credentials here")
New-ADUser #userParams

Powershell - Azure AD : User creation - PasswordProfile error message

I am doing some tests to manage Azure AD users and groups with Powershell.
Unfortunately, i have an issue when i try to create an user. Here my code :
#Specifies the user's password profile.
$PasswordProfile=New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "xxxx"
#Create a AzureAD user account
PS C:\Windows\system32> New-AzureADUser -DisplayName "Power SHELL"
-GivenName "Power" -SurName "SHELL"
-UserPrincipalName power.shell#xxxx.xx -UsageLocation FR
-MailNickName Power Shell -PasswordProfile $PasswordProfile
-AccountEnabled $true
When I validate the PasswordProfile, I have this error message :
New-AzureADUser: Failed to bind parameter 'PasswordProfile'. Cannot convert value '$PasswordProfile' of type 'System.String to type “Microsoft.Open.AzureAD.Model.PasswordProfile”.
I look in a lot of forum but i can't find any solution to make it works.
Thanks for your help.
Geoffrey
I could create the user successfully with the commands you have provided and as per microsoftDocs:
Result:
I could reproduce the issue with error:
Cannot bind parameter 'PasswordProfile'.
" value of type "System.String" to type "Microsoft.Open.AzureAD.Model.PasswordProfile".
when i actually placed quotes around $PasswordProfile like below
New-AzureADUser -DisplayName "xxx" -GivenName "xx" -SurName "xx" -UserPrincipalName xxxx.onmicrosoft.com -UsageLocation US -MailNickName navy -PasswordProfile "$PasswordProfile" -AccountEnabled $true
So please try by placing $PasswordProfile in quotes in your case to resolve the issue.
-PasswordProfile "$PasswordProfile"
similar case here : Cannot convert 'System.Object[]' to the type .. | techcommunity.microsoft.com
Please make sure password is valid and check if string as input type for Parameter somehting like here
or
Try this way:
$PasswordProfile = New-Object -TypeName
Microsoft.Open.AzureAD.Model.PasswordProfile
$PasswordProfile.Password = "Ixxxxxxxk"
$params = #{
AccountEnabled = $true
DisplayName = "xxxn"
PasswordProfile = $PasswordProfile
UserPrincipalName = "xxx#xxxxxx.onmicrosoft.com"
MailNickName = "xxxxx"
}
New-AzureADUser #params
References:
set-azureaduserlicense-cannot-bind-parameter-assignedlicenses

sudent, invalid name for New-ADUser multi user creation script

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.

Not able to set the "PasswordNeverExpires" parameter to true in Powershell 2.0

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.

PowerShell New-ADUser fails in cycle

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.