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

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.

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

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.

Student Script for creating new users error :System.String' to the type 'System.Management.Automation.SwitchParameter

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 : Cannot convert 'System.String' to the type 'System.Management.Automation.SwitchParameter' required by parameter
'Confirm'.
At C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\Bamboo Attributes form a csv.ps1:68 char:28
+ New-ADUser #NewUserParms
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-ADUser], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.ActiveDirectory.Management.Commands.NewADUser
I have no idea what this is haha, I've tried adding an erroraction stop to the new-aduser but that didn't have any effect
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'
#Bamboo Attributes from a .csv
#Enter a path to your import CSV file
$ADUsers = Import-csv 'C:\Users\Administrator\Documents\GitHub\cyclone-internal-user-sync-1\documentation\SampleUserAttributes.csv'
#$apiRequest = Get-Content -Raw -Path C:\Users\alexh\Documents\GitHub\cyclone-internal-user-sync-1\cyclone-internal-user-sync-1\fake-api-query.json | ConvertFrom-Json
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";
'co' = $User.Country;
'company' = $User.CompanyName;
'countryCode' = $user.countryCode;
'department' = $user.OrgDepartmentName;
'Employeeid' = $user.EmployeeId;
'exstentionAttribute1' = $user.ExstentionNumber;
'ipPhone' = $user.ExstentionNumber;
'L' = $user.location;
'mail' = $user.Email;
'mobile' = $user.Mobile;
'Manager' = $user.Manager;
'physicalDeliveryOffice' = $user.Branch;
'postalCode' = $user.PostalCode;
'postOfficeBox' = $user.PostOfficeBox;
'proxyAddresses' = $user.ProxyEmail;
'scriptPath' = $user.scriptPath;
'st' = $user.StreetName;
'Title' = $user.Title
}
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
}
}
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
A little known fact about PowerShell is that you don't need to use the whole parameter name. You can use the partial name and as long as it matches only one parameter name, that's what PowerShell assumes you mean.
The one it's choking on is this:
'co' = $User.Country;
If you look at the documentation for New-ADUser, it does not have a parameter called co. So PowerShell assumes it's a partial match to a known parameter, and the closest match is -Confirm. And the value in $User.Country doesn't make any sense for the -Confirm parameter, so it throws the error.
You will have to use the -OtherAttributes parameter to set all the other attributes that New-ADUser doesn't have a dedicated parameter for:
$NewUserParms = #{
...
'OtherAttributes = # {
'co' = $User.Country;
'exstentionAttribute1' = $user.ExstentionNumber;
...
}
...
}
As commented in this and previous questions, you are using New-ADUser $NewUserParms, where it should be New-ADUser #NewUserParms.
Also, to catch errors (you did add -ErrorAction Stop), you need to put that inside a try{..} catch{..} block.
I would also change the syntax you use for the -Filter parameter. Instead of using a scriptblock syntax {something -eq someotherthing}, you should create a string like "something -eq 'someotherthing'"
Try:
# define some 'constants'
$csvFile = 'X:\Folder\NewUsers.csv' # Enter a path to your import CSV file
$invalidCharacters = '[^a-z_.]' # identifies anything that's _not_ a-z or underscore or .
$DefaultPassword = 'Pa$$w0rd'
$securePassword = ConvertTo-SecureString -String $DefaultPassword -AsPlainText -Force
# read the input csv and loop through
Import-Csv -Path $csvFile | ForEach-Object {
$firstName = $_.FirstName.Trim()
$surname = $_.Surname.Trim()
$username = ('{0}.{1}' -f $firstName, $surname) -replace $invalidCharacters
# test if a user with that name already exists
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
Write-Warning "A user account $username already exist in Active Directory."
}
else {
Write-Host "Creating user $username"
$NewUserParms = #{
'SamAccountName' = $username
'Name' = "$firstname $surname"
'DisplayName' = "$firstname $surname"
'UserPrincipalName' = "$username#domain.com"
'GivenName' = $firstname
'Surname' = $surname
'EmailAddress' = $_.Email
'AccountPassword' = $securePassword
'Enabled' = $true
'Path' = "OU=Users,DC=domain,DC=com"
# add other properties to set from the CSV here.
# make sure you get the parameter data types correct and always check here:
# https://learn.microsoft.com/en-us/powershell/module/addsadministration/new-aduser?view=win10-ps#parameters
# switch parameters for the cmdlet can also be entered with a value $false or $true
}
try {
# '-ErrorAction Stop' ensures that also non-terminating errors get handled in the catch block
New-ADUser #NewUserParms -ErrorAction Stop
}
catch {
# something bad happened. Change 'Write-Warning' into 'throw' if you want your script to exit here
# inside a catch block, the '$_' automatic variable represents the actual exception object.
Write-Warning "Could not create account $username. $($_.Exception.Message)"
}
}
}

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.