I am prepping a script for our accounts management team that'll create users accounts fairly quickly. I seem to always get an error stating:
New-ADUser : A value for the attribute was not in the acceptable range of values
I have looked online and through here a bit but some of the solutions that others posted didn't work for me. The code is below:
Write-Host "New Business Services Account" -ForegroundColor Green
$Name = Read-Host "Enter First and Last Name"
$DisplayName = $Name
$GivenName = Read-Host "Enter First Name"
$Surname = Read-Host "Enter Last Name"
$EmailAddress = Read-Host "Enter Email Address"
$SamAccountName = Read-Host "Enter SamAccountName"
#$UserPrincipalName = $GivenName.$Surname + "#{entrustenergy}.com"
$Office = Read-Host "Enter Office"
$City = "Houston"
$State = "TX"
$ZipCode = Read-Host "Enter Zip Code"
$Country = "United States"
$Company = "Entrust Energy, Inc."
$JobTitle = Read-Host "Enter Job Title"
$Department = Read-Host "Enter Department"
$Manager = Read-Host "Enter Managers Username"
$Path = "PathOUisHere"
$Password = Read-Host "Enter Password"
New-ADUser -Name "$Name" -GivenName "$GivenName" -Surname "$Surname" `
-DisplayName "$DisplayName" -EmailAddress "$EmailAddress" `
-SamAccountName "$SamAccountName" -StreetAddress "$Address" -City "$City" `
-State "$State" -PostalCode "$ZipCode" -Country "$Country" `
-Company "$Company" -Title "$JobTitle" -Department "$Department `
-Manager "$Manager" -Path "$Path" -Enabled $true `
-AccountPassword (ConvertTo-SecureString "$Password" -AsPlainText -Force) `
-ChangePasswordAtLogon $true -PassThru
You're passing '-StreetAddress "$Address"' but it's never supplied in the read-host section.
Going out on a limb I'd guess that the error is caused by the value you provide for the property -Country. From the documentation:
Country
Specifies the country or region code for the user's language of choice. This parameter sets the Country property of a user object. The LDAP Display Name (ldapDisplayName) of this property is "c". This value is not used by Windows 2000.
The following example shows how set this parameter.
-Country "IN"
Change $Country = "United States" to $Country = "US" and the error should disappear.
See also this answer to a related question.
Related
FIXED: I did have to change if ($null -eq $FoundUser) and then if essentiall NULL -eq NULL, that user doesn't exist...
SORRY
I would really love some help as I've on/off been struggling with this logic with Get-ADUser for user creation.
I'm using Powershell 7.0 - 7.2.1 (latter currently) and having this problem with VSCode and running it in "console". We have a 2008 R2 forest but 2016 and 2019 DCs.
Essentially "Get-ADUser -Filter" doesn't return any value. I'm trying to use an if statement for if $null -ne $SamAccountName.
Any thoughts?
I thought I found the answer here but no luck for me.
$Users = Import-Csv -delimiter "`t" -Path "C:\Users\michel_m\Documents\Scripts\PowerShell\Staff\StaffData.txt"
#$sam = ""
#Generate data to use in creating user below
foreach ($User in $Users) {
$SAMAccount = $User.Username
$Filter = "sAmAccountname -eq '$SamAccount'
$FoundUser = Get-ADUser -Filter $Filter
Write-Host "HERE IS" $FoundUser
$results = $FoundUser.SamAccountName
#if ($null -ne $FoundUser)
if ($null -ne $results)
{
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
#NewUser_Function
($Dates + " - " + $user.username + " has been created") | out-file -filepath $OutputFile1 -append
#Write-Host "Pause 15 seconds"
Start-Sleep 15
Write-Host $user.username + " Has been created"
$Body = $user.username + " Has been created"
#schtasks.exe /run /s "OHDC01" /tn "GADS Sync - Users"
}
else
{
Write-Host $Filter
Write-Host $results "Are the results"
Write-Host $User "is the user"
Write-Host $SAMAccount "Is the SAM user"
Write-Host $FoundUser "Is the found user"
Write-Host $null is null
write-host $user.username + " already exists"
($Dates + " - " + $user.username + " already exists") | out-file -filepath $OutputFile2 -append
$Body = $user.username + " already exists",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\",
"\\OHDC01\C$\Scripts\StaffCreation\NewStaff\"
}
}
Output
HERE IS
sAmAccountname -like 'mangold_m' | Select-object SamAccountName
Are the results
#{FirstName=Michelle; LastName=Mangold; BuildingName=OAK; Position=Aide; Username=mangold_m; Email=mangold_m#Wonderfullife.org} is the user
mangold_m Is the SAM user
Is the found user
is null
mangold_m + already exists
HERE IS
sAmAccountname -like 'metzner_m' | Select-object SamAccountName
Are the results
#{FirstName=Melissa; LastName=Metzner; BuildingName=OHHS; Position=Aide; Username=metzner_m; Email=metzner_m#Wonderfullife.org} is the user
metzner_m Is the SAM user
Is the found user
is null
metzner_m + already exists
Thank you for updating you got your solution.
Here I also have tried from my side you can also use this small PowerShell script for validating the user existance.
$Users = Import-Csv -Path "C:\Users\RahulShaw\test.csv"
Foreach ($User in $Users){
$Username = $User.Username
$FoundUser = Get-ADUser -Filter "sAmAccountName -eq '$Username'"
$results = $FoundUser.SamAccountName
Write-Host $results
if($null -eq $FoundUser){
write-host "Username '$Username' does not yet exist in active directory"
}
else{
write-host "Username '$Username' exist in active directory"
}
}
I am attempting to prompt a user for input and then validate if the users input matches one of two different options, and will exit if a correct input was not given.
In the example, I am asking the user to enter 'BOB' or 'TOM' as valid inputs, however when I run this code I will always get the message 'Server type not entered correctly', even when I enter BOB as an input for the prompt.
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
If ($ServerType -ne "BOB" -Or $ServerType -ne "TOM")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
I have also tried
If (($ServerType -ne "BOB") -or ($ServerType -ne "TOM"))
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
However, when I only test for one value it works:
If ($ServerType -ne "BOB")
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Any ideas why I might be getting this?
As in my comment, the logical operator in this case should be -and but allow me to give you 2 examples where your validation could be improved.
First one is using the -match \ -notmatch comparison operators, which allows the use of regex:
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
if($ServerType -notmatch '^(bob|tom)$')
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Second one, is using a ValidateSet attribute:
try
{
[validateset('bob','tom')]
$ServerType = Read-Host -Prompt 'Enter Server Type (BOB or TOM)'
}
catch
{
Write-Host -NoNewLine 'Server type not entered correctly'
}
Below is section of a large script that configures range of tasks remotely on a Active Directory server.
The script asks the user to enter OU name, saves it in a variable and passes it to AD server via Invoke-Command and $Using scope to transfer variable value to remote host and process the request
$value = Read-Host -Prompt "Enter Unique Name"
Invoke-Command -Session $testsession -ScriptBlock {
$DDN = "DC=Test,DC=net"
$OUdn = "OU=MainOU,"+$DDN
$COU = $Using:value
$Cdn = "OU="+$COU
$CPath = $Cdn+","+$OUdn
While ($true) {
Write-Host "Checking existence of OU"
if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$CPath'") {
Write-Host "$COU OU exists."
$COU = $Null
$Cdn = $Null
$Cpath = $Null
$COU = Read-Host -Prompt "Enter Unique Name"
$Cdn="OU="+$CustOU
$CPath=$Cdn+","+OUdn
}else {
Write-Host "$COU is new"
New-ADOrganizationalUnit $COU -path $OUdn
if (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$CPath'") {
write-host " $COU is created "
}
Break
}
}
}
It gives the desired result when it is run separately and creates OU with the name provided under "Main OU". However, when it is combined with the main script it throws exception error. Main script also prompts to enter some more info which are used in other sections successfully but just not working in this section.
Am I missing anything? Your suggestions and helps are appreciated.
Object reference not set to an instance of an object.
+ CategoryInfo : NotSpecified: (:) [Get-ADOrganizationalUnit], NullReferenceException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.NullReferenceException,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit
This will help you understand why you're getting the error and will also help you in future scripts:
try
{
New-ADOrganizationalUnit $COU -path $OUdn
}
catch
{
#(
"Failed to create New Organizational Unit:"
"$_"
"Value for `$COU was: $COU"
"Value for `$OUdn was: $OUdn"
) | Out-String | Write-Warning
break
}
For more info: about_Try_Catch_Finally
As a side note, I don't see $CustOU being previously defined and I believe this a typo $Cdn+","+OUdn.
Can't seem to figure out what is causing the error with script below with the "New-ADUser" syntax. Not sure if anybody can spot the error?
"New-ADUser : The object name has bad syntax
At D:\ScriptPath\importadusersAndMoveOU.ps1:33 char:3"
The script works if I remove the "$NewOU" variable and have the users imported into the default "users" OU.
# Import active directory module for running AD cmdlets
Import-Module activedirectory
#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv 'D:\CSVPATH\adusers.csv'
$NewOU = New-ADOrganizationalUnit -Name "ADMINS"
#Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a
variable as below
$DomainName = Get-ADDomain -current LocalComputer
$Username = $User.username
$Password = "TestPassword12345"
$Firstname = $User.firstname
$Lastname = $User.lastname
$OU = $NewOU+","+$DomainName.DistinguishedName
$upn = $Username+"#"+$DomainName.DNSRoot
#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
#If user does exist, give a warning
Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
#Account will be created in the OU provided by the $OU variable read from the CSV file
New-ADUser `
-SamAccountName $Username `
-UserPrincipalName $upn `
-Name "$Firstname $Lastname" `
-GivenName $Firstname `
-Surname $Lastname `
-Enabled $True `
-DisplayName "$Lastname, $Firstname" `
-Path $OU `
-AccountPassword (convertto-securestring $Password -AsPlainText -Force) -ChangePasswordAtLogon $True
Add-ADGroupMember "domain admins" $username
Add-ADGroupMember "enterprise admins" $Username
}
}
The New-ADOrganizationalUnit -Name "ADMINS" command creates a new OU under the default NC head for the domain.
If you want that elsewhere, you should use the -Path <DistinghuisedName of Parent OU> parameter.
However, as Drew Lean already commented, this code does not check if the OU exists before trying to create it, so a quick test might be in order here:
[adsi]::Exists("LDAP://OU=ADMINS,DC=domain,DC=com")
or
Get-ADOrganizationalUnit -Filter "distinguishedName -eq 'OU=ADMINS,DC=domain,DC=com'"
# don't filter on 'Name' because it is more than likely you have several OUs with the same name
Next, the part where you construct the distinguishedName for variable $OU results in a badly formatted string.
$OU = $NewOU+","+$DomainName.DistinguishedName will result in "ADMINS,DC=domain,DC=com" which is not a valid DistinghuishedName, hence the error The object name has bad syntax
Try getting the DN of the existing OU first and if that does not exist, capture it after the creation and store the DistinghuishedName in variable $OU
something like this:
$OU = "OU=ADMINS,DC=domain,DC=com"
if (-not (Get-ADOrganizationalUnit -Filter "distinguishedName -eq '$OU'")) {
$NewOU = New-ADOrganizationalUnit -Name "ADMINS" -PassThru
$OU = $NewOU.DistinghuishedName
}
ps. The Identity parameter for Get-ADOrganizationalUnit must be one of:
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A Security Account Manager account name (sAMAccountName)
I have got 2 powershell scripts, which I have mentioned below. I am looking for a way to combine both of these scripts. However I am unable to do so as one of the script is using CIM method and the other one is using the WMI method.
What I am trying to accomplish, is to provide the last reboot time and free space available of the same server (User has to enter the server name and on pressing Enter it shows the last reboot time and free space available).
Script 1 (CIM Method) :
$Server = Read-Host -Prompt 'Input your server name'
Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server | select csname, lastbootuptime
Read-Host -Prompt "Press Enter to exit"
Script 2 (WMI Method) :
$Server = Read-Host -Prompt 'Input your server name'
Get-WMIObject Win32_Logicaldisk -ComputerName $Server | Select PSComputername,DeviceID, #{Name="Total_Size_GB";Expression={$_.Size/1GB -as [int]}}, #{Name="Free_Space_GB";Expression={[math]::Round($_.Freespace/1GB,2)}}
Read-Host -Prompt "Press Enter to exit"
Store the results of your queries in a variable. Then create a psobject with the values you are interested in from each function. You can find out more about New-Object psobject here.
$Server = Read-Host -Prompt 'Input your server name'
$myCimResp = Get-CimInstance -ClassName win32_operatingsystem -ComputerName $Server | select csname, lastbootuptime
$myWmiResp = Get-WMIObject Win32_Logicaldisk -ComputerName $Server | Select PSComputername,DeviceID, #{Name="Total_Size_GB";Expression={$_.Size/1GB -as [int]}}, #{Name="Free_Space_GB";Expression={[math]::Round($_.Freespace/1GB,2)}}
$theThingIActuallyWant = New-Object psobject -Property #{
LastRebootTime = $myCimResp.lastbootuptime
FreeSpace = $myWmiResp.Free_Space_GB
}
# A couple of ways to print; delete 1, keep 1
Write-Output $theThingIActuallyWant # Print to screen with implicit rules
$theThingIActuallyWant | Format-Table # Print to screen with explicit table formatting
Read-Host -Prompt "Press Enter to exit"