Powershell user creation script - leave fields blank? - powershell

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

Related

Create New User via PowerShell

I am working on a script creating a new user via PowerShell with user (creator) input. The input I am looking for is for the first name and last name along with some attributes. I would like the samaccountname and the UPN to be auto created from the input. Not sure if this can be done completely but would like to get some input on my current script. I highlighted firstinital as a placeholder to show what I am trying to accomplish.
new-aduser -givenname($givenname = read-host "Input Firstname") -surname($surname = read-host "Input Lastname") -samAccountName ("***firstinitial***"+"$._surname") -userprincipalname "$._surname+"#domain.com" -path "OUName" -whatif
Alrighty thanks for the help below. I was able to do a few more searches and can up with the following. All looks to work except the distingushed name comes up as a single name instead of a space between the first and last name.
#User info entered
$first = Read-Host "First name"
$last = Read-Host "Last name"
$title = Read-Host "Title"
$location = Read-Host "Location"
$department = Read-Host "Business Practice"
$password = read-host -assecurestring "Password"
#Create new user
$Attributes = #{
Enabled = $true
ChangePasswordAtLogon = $false
UserPrincipalName = $first.split(" ")[0]+$last+"#domain.com"
Name = $first+$last
GivenName = $first
Surname = $last
DisplayName = "$first "+" $last"
Office = $location
Department = $department
Title = $title
samAccountName = $first.split(" ")[0] + $last
AccountPassword = $password
}
New-ADUser #Attributes -whatif
You can add this to get the $_.givenName as the first initial:
$gn = (read-host "Input Firstname")
$sn = (read-host "Input Lastname")
new-aduser -givenname $gn -surname $sn -samAccountName $gn.split(" ")[0]+$sn -userprincipalname $sn+"#kfriese.com" -path "OUName" -whatif
Here is a more advanced and robust way to do it: a custom function, that makes use of PowerShell integrated functionality.
It uses attributes that make the parameters mandatory, so user input will automatically be inquired when the function is called. Also a validation attribute to make sure the input is not empty and has no invalid characters (you might want to adjust the regex according to your needs).
The arguments for New-ADUser are passed using splatting. The rest is pretty straight-forward...
function makeuser {
param(
[Parameter(Mandatory, Position = 0)]
[ValidatePattern("[a-z]+")]
[string]$GivenName,
[Parameter(Mandatory, Position = 1)]
[ValidatePattern("[a-z]+")]
[string]$Surname
)
$params = #{
GivenName = $GivenName
Surname = $Surname
SamAccountName = $GivenName[0] + $Surname
UserPrincipalName = $Surname + "#kfriese.com"
Path = "OUName"
}
New-AdUser #params
}
To call the function, just type (parameter values will be inquired automatically)
makeuser
Or specify the values explicitly:
makeuser -GivenName Foo -Surname Bar
# or
makeuser foo bar

Set-User: A parameter cannot be found that matches parameter name 'Title' using Connect-ExchangeOnline

I am writing a script that will update Exchange mailbox attributes from a CSV file. When I run my script I get a 'A parameter cannot be found that matches parameter name 'Title'." error. Any ideas. I am tring to change The title property within the organisation tab in Exchange.
I know what the error message means but I can't find anywhere what the syntax is for changing the title attribute.
Script:
# Updates AD user attributes from CSV file
$Credential = Get-Credential
Connect-ExchangeOnline -Credential $Credential
# Load data from file.csv
$ADUsers = Import-csv file_path
# Count variable for number of users update
$count = 0
# Go through each row that has user data in the CSV we just imported
ForEach($User in $ADUsers)
{
# Ppopulate hash table for Get-ADUser splatting:
$GetParams =
#{
Identity = $User.Username
}
# Initialize hash table for Set-ADUser splatting:
$SetParams =
#{
Title = $User.Title
}
# Check to see if the user already exists in AD. If they do, we update.
if ( Get-EXORecipient #GetParams)
{
# Set User attributes
Set-User #SetParams -WhatIf
# Print that the user was updated
Write-Host -ForegroundColor Yellow "$User - User attributes have been updated."
# Update Count
$count += 1
}
}
# Print the number of updated users
Write-Host $count "Users have been updated" -ForegroundColor Green
Error Message:
A parameter cannot be found that matches parameter name 'Title'.
+ CategoryInfo : InvalidArgument: (:) [Set-Mailbox], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Set-Mailbox
+ PSComputerName : outlook.office365.com
Your params for Set-User doesn't contain -Identity so PowerShell doesn't know to whom the title should be set. You need to add it:
$SetParams =
#{
Identity = $User.Username
Title = $User.Title
}
Make sure that Username contains valid identity, so the user can be determined based on it.

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.

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

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.

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.