New-ADUser Access denied error with Powershell script - powershell

When I run .ps1 I have written to create AD accounts and Mailboxes based on arguments passed to it from a WinForm I am consistently getting the error:
New-ADUser : Access is denied
The script is run when someone clicks a button in a winform and below is the command the button issues:
Powershell.exe "C:\Users\admin\Scripts\usercreationscript.ps1" -department 'Accounting - North America' -GivenName 'test' -Surname 'testlast' -path 'OU=users,DC=domain1,DC=com' -Title 'Sys Admin' -Office 'NJ' -StreetAddress '123 ST' -City 'Moorestown' -PostalCode '08057' -State 'NJ' -Manager 'Jacobb' -MercuryFlag 0 -MirroredUser 'jacobb' -username 'test.testlast'
I have set the execution policy on the remote servers to unrestricted and have also run the Enable-PSRemoting command. The credentials that I supply when prompted are domain administrator credentials. I have also set the trusted hosts to *
When I open the script in Powershell ISE I can connect to remote servers with the Enter-PSSession command I have in the script and can successfully create AD accounts.
I am at a loss as to what is causing the issue.
Full script:
param( [string]$username, [string]$department, [string]$GivenName, [string]$Surname, [string]$path, [string]$Title, [string]$Office, [string]$StreetAddress, [string]$City, [string]$PostalCode, [string]$State, [string]$Manager, [string]$MercuryFlag, [string]$MirroredUser)
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
#"No Administrative rights, it will display a popup window asking user for Admin rights"
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments
break
}
#"After user clicked Yes on the popup, your file will be reopened with Admin rights"
#"Put your code here"
#region - Required Functions - ONLY MODIFY AFTER BACKING UP COPY OF SCRIPT
function connect-Domain1AD {
Enter-PSSession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
}
function Connect-Domain1Exchange {
$domain1session = New-PSSession -Authentication Kerberos -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://exchange1.domain1.com/Powershell' -Credential $Credentialdomain1
Import-PSSession $domain1session
}
function Connect-Domain2Exchange {
$session = New-PSSession -Authentication Kerberos -ConnectionUri 'http://exchange1.domain2.com/Powershell' -Credential $Credentialdomain2
Enter-PSSession $Session
}
function Connect-Domain2AD {
Enter-PSSession -ComputerName Dc1.domain2.com -Credential $Credentialdomain2
}
function New-Domain2User{
$userroot ="\\arizona\RemoteAppProfiles\$USERNAME"
New-ADUser `
-name ($givenname + " " + $surname) `
-SamAccountName $Username `
-department $department `
-Title $title `
-office $office `
-StreetAddress $street `
-city $city `
-State $state `
-PostalCode $PostalCode `
-path "OU=users,DC=domain2,DC=com" `
-GivenName $GivenName `
-Surname $Surname `
-DisplayName ($givenname + " " + $surname) `
-userPrincipalName ($username + "#domain2.com") `
-AccountPassword (ConvertTo-SecureString "A temp password." -AsPlainText -force) `
-Enabled $true `
-PasswordNeverExpires $true `
-CannotChangePassword $false `
-ProfilePath \\arizona\RemoteAppProfiles\$Username\ `
-HomeDrive U: `
-HomeDirectory $userroot
Set-ADUser $USERNAME -Add #{extensionattribute14=$username}
}
function New-Domain1User {
New-aduser -name ($givenname + " " + $surname) `
-GivenName $givenname `
-Surname $surname `
-DisplayName ($givenname + " " + $surname) `
-SamAccountName $Username `
-userPrincipalName ($username + "#goevo.com") `
-path $path `
-AccountPassword (ConvertTo-SecureString "A temp password." -AsPlainText -force) `
-Enabled $true `
-PasswordNeverExpires $false `
-CannotChangePassword $false `
-department $department `
-Title $title `
-office $office `
-StreetAddress $street `
-city $city `
-State $state `
-PostalCode $zipcode `
-Manager $Manager
}
function New-Domain1Mailbox {
Enable-mailbox -identity $username
Set-Mailbox -identity $username `
-customAttribute1 "Domain1" `
-customAttribute2 "user" `
-customAttribute3 "Internal" `
-customAttribute5 $office `
-customattribute6 $department `
-customattribute7 $ca7 `
-customattribute8 $ca8
}
#endregion - Required Functions
Write-Host $MercuryFlag
If($MercuryFlag -eq '1' ){
Set-variable -name Credentialdomain2 -value $Host.ui.PromptForCredential("Need Domain2 credentials", "Please enter your Domain2 user name and password:", "", "Domain2.com") -scope global
Connect-Domain2AD
import-module activedirectory
New-Domain2User
Exit-PSSession
get-pssession | remove-pssession
Set-variable -name Credentialdomain1 -value $Host.ui.PromptForCredential("Need Domain1 credentials", "Please enter your Domain1 user name and password:", "", "Domain1.com") -scope global
connect-Domain1AD
New-Domain1User
Exit-PSSession
get-pssession | remove-pssession
Connect-Domain1Exchange
New-Domain1Mailbox
Exit-PSSession
get-pssession | remove-pssession
}
else {
Set-variable -name Credentialdomain1 -value $Host.ui.PromptForCredential("Need Domain1 credentials", "Please enter your Domain1 user name and password:", "", "Domain1.com") -scope global
connect-Domain1AD
New-Domain1User
Exit-PSSession
get-pssession | remove-pssession
Connect-Domain1Exchange
New-Domain1Mailbox
Exit-PSSession
get-pssession | remove-pssession
}

I was able to fix it by changing
:
function connect-Domain1AD {
Enter-PSSession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
}
to
function connect-Domain1AD {
$domain1ad = new-pssession -ComputerName DC1.domain1.com -Credential $Credentialdomain1
Invoke-Command –Session $domain1ad –ScriptBlock {Import-Module ActiveDir*}
Import-PSSession –Session $domain1ad –Module ActiveDir* -AllowClobber
}

Related

Having problems getting script to continue using workflow after dcpromo /unattend

Workflow Rename-DC
{
dcpromo /unattend:C:\Payload\AnswerFile.xml
Checkpoint-Workflow
New-ADOrganizationalUnit -Name "Admin" -Path "DC=ProjectX,DC=com"
Add-KdsRootKey EffectiveImmediately
New-ADServiceAccount -Name "Test Account" -DNSHostName "DC1.ProjectX.com" -Enabled $true
New-ADUser -Name "HelpDesk" -GivenName "Helpdesk" -Surname "" -SamAccountName helpdesk -UserprincipalName helpdesk#ProjectX.com -Path "OU=Admin,DC=ProjectX,DC=com"
Unregister-ScheduledJob -Name RenameDCResume
}
$Admin = "Administartor"
$Password = ConvertTo-SecureString -String "Passw0rd" -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential($Admin, $Password)
$AtStartup = New-JobTrigger -AtStartup
Register-ScheduledJob -Name RenameDCResume `
-Credential $Cred `
-Trigger $AtStartup `
-ScriptBlock {Import-Module PSWorkflow; `
Get-Job -Name RenameDomainController -State Suspended `
| Resume-Job}
Rename-DC -JobName RenameDomainController
Looking for some help with my workflow in PowerShell. the plan is to get the script to continue after the computer reboots for installation of the DC at line 3. However, the script doesn't seem to be continuing as planned at start up. Any ideas what I can do to correct this? Also, is the checkpoint after the dcpromo correct? Will it still take a checkpoint or will it ignore this as the reboot has already begun? would a PSPersist work better? Thanks in anticipation.

ADSI not validating correctly?

I have a CSV with 1500+ users there are 30 users per class OU, and then 6 class OU's per Intake OU. What I'm trying to achieve is, foreach (user in CSV), check if OU exists, then check if parent OU exists, create the parent OU only if it doesn't exist, then create the OU, then create the user, or just create the user if the OU exists.
Here is the code I'm using:
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
$CSV = Import-Csv "C:\Scripts\AddPupils.csv"
foreach ($user in $CSV) {
# Variables
$GivenName = $user.GivenName
$SurName = $user.SurName
$UserName = $user.UserName
$Class = $user.YearClass
$Intake = $user.Intake
$DisplayName = $GivenName+" "+$SurName
# Create User
$UserOUParent = "OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$UserOU = "OU=Class "+$Class.Substring(1,1)+",OU=Year "+$iIntake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=com"
$NewUserOUParentCheck = [ADSI]::Exists("LDAP://$UserOUParent")
$NewUserOUCheck = [ADSI]::Exists("LDAP://$UserOU")
if ($NewUserOUCheck -eq $false){
if ($NewUserOUParentCheck -eq $false){
"Create Parent Ou"
New-ADOrganizationalUnit `
-Name ("Year "+$Intake+" Intake") `
-Path "OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"Create OU"
New-ADOrganizationalUnit `
-Name ("Class "+$Class.Substring(1,1)) `
-Path ("OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProtectedFromAccidentalDeletion $False
}
"Create User"
New-ADUser `
-Name $DisplayName `
-SurName $SurName `
-GivenName $GivenName `
-DisplayName $DisplayName `
-SamAccountName $UserName `
-UserPrincipalName ($UserName+"#Zulbag.com") `
-AccountPassword (ConvertTo-SecureString "Testing123" -AsPlainText -force) `
-CannotChangePassword $true `
-ChangePasswordAtLogon $false `
-PasswordNeverExpires $true `
-EmailAddress ($UserName+"#Zulbag.com") `
-Country "GB" `
-Path ("OU=Class "+$Class.Substring(1,1)+",OU=Year "+$Intake+" Intake,OU=Students,OU=Users,OU=Roding,DC=Zulbag,DC=Com") `
-ProfilePath ("D:\Shares\User Accounts\Students\Intake Year "+$Intake+"\Class "+$Class.Substring(1,1)+"\Profiles\"+$DisplayName) `
-Enabled $true
Start-Sleep -Seconds 5
# Add To Group
$Group = "CN=Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)+",OU=Intake "+$Intake+",OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$GroupOU = "OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com"
$NewGroupCheck = [ADSI]::Exists("LDAP://$Group")
$NewGroupOUCheck = [ADSI]::Exists("LDAP://$GroupOU")
if ($NewGroupCheck -eq $false) {
if ($NewGroupOUCheck -eq $false) {
"Create OU"
New-ADOrganizationalUnit `
-Name ("Intake "+$Intake) `
-Path "OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com" `
-ProtectedFromAccidentalDeletion $False
}
"create Group"
New-ADGroup `
-Name ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) `
-GroupScope "Global" `
-Path ("OU=Intake "+$Intake+",OU=Folder Redirection Groups,OU=Security Groups,OU=Roding,DC=Zulbag,DC=Com")
}
"Add Member"
Add-ADGroupMember ("Redirection "+$Intake.Substring(2,2)+$Class.Substring(1,1)) $UserName
}
pause
Sample CSV:
GivenName,SurName,Class,UserName,Intake
Ali,Grisdale,1B,AGris,2016
Ayomiposi,Olayera,1B,AOlay,2016
In tests with Write-Output, the [ADSI] validates correctly but it appears to be validating it incorrectly here, the error message I keep getting is:
New-ADOrganizationalUnit : An attempt was made to add an object to the
directory with a name that is already in use
At C:\Scripts\AddPupils-Afzal.ps1:24 char:13
+ New-ADOrganizationalUnit
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (OU=Year 2016 In...C=Zulbag,DC=Com:String) [New-ADOrganizationalUnit], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8305,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnitdirectory
It successfully creates the parent OU, class OU and user, but fails to create the second user, instead validates the OU incorrectly again.
Any Ideas?
Check the script for path errors!

PowerShell Script Runs Locally, but Errors on Remote

I have a PowerShell script I am writing to create new users in our domain, as well as email address. The script works when I run it directly on Exchange. However, if I try to do it from my local PC either with Enter-PSSession or Invoke-Command I get the error:
The term 'Get-ADUser' is not recognized as the name of a cmdlet...
Running that same command from the local machine does work. And running that command on the remote machine works, just not if I run the script remotely.
Here is my script:
$cred = Get-Credential
$first_name = Read-Host -Prompt "What is the new user's first name?"
$last_name = Read-Host -Prompt "What is the new user's last name?"
$copy_from = Read-Host -Prompt "Copy from other user (leave blank if not)?"
$password = Read-Host -Prompt "New user's password?"
$ss_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$new_user_name = $last_name.Substring(0,3) + $first_name.Substring(0,2)
$new_user_name = $new_user_name.ToLower()
Write-Host "Creating user $new_user_name..." -ForegroundColor Green
if ([string]::IsNullOrEmpty($copy_from))
{
Write-Host "Setting up new user (not copying...)" -ForegroundColor Yellow
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -SamAccountName $new_user_name -PassThru | Enable-ADAccount
}
else
{
$copy_from_user = Get-ADUser -Identity $copy_from
Write-Host "Copying user from: " $copy_from_user.Name -ForegroundColor Yellow
$ou = $copy_from_user.DistinguishedName -replace '^cn=.+?(?<!\\),'
New-ADUser -Name "$first_name $last_name" -AccountPassword $ss_password -Path $ou -SamAccountName $new_user_name -PassThru | Enable-ADAccount
$new_user = Get-ADUser -Identity $new_user_name
#Time to copy their group memberships
Get-ADUser -Identity $copy_from -Properties memberof | Select-Object -ExpandProperty memberof | Add-ADGroupMember -Members $new_user_name
}
$pn = $new_user_name + "#INDY"
Set-ADUser -Identity $new_user_name -GivenName $first_name -Surname $last_name -UserPrincipalName $pn
#Now create email
$email_select = Read-Host -Prompt "Select email domain (1. Woodmizer; 2. Lastec; 3. Brightstone)"
if ($email_select -eq 2)
{
$domain = "#lastec.com"
}
elseif ($email_select -eq 3)
{
$domain = "#brightstoneabrasives.com"
}
else
{
$domain = "#woodmizer.com"
}
$email_address1 = $first_name.Substring(0,1) + $last_name + $domain
Write-Host "Creating mailbox $email_address1..." -ForegroundColor Green
Enable-Mailbox -Identity $new_user_name -Database "Mailbox Database 1188513962"
Start-Sleep -s 10
Get-Mailbox -Identity $new_user_name | Set-Mailbox -EmailAddresses #{add="$email_address1"} -EMailAddressPolicyEnabled $false
Get-Mailbox -Identity $new_user_name | Set-Mailbox -PrimarySmtpAddress $email_address1 -EmailAddressPolicyEnabled $false
Write-Host "Finished." -ForegroundColor Green
If you want this script to run on machines that don't have the Active Directory module, you can simply add this to the top of your script to import the cmdlets via session..
$cred = Get-Credential "DOMAIN\adminuser"
$ADsession = New-PSSession -ComputerName DOMAINCONTROLLERNAME -Credential $cred
Import-Module -PSSession $ADsession ActiveDirectory
I also notice you're trying to run Exchange cmdlets..
$exchSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://EXCHANGESERVER/PowerShell/" -Authentication Kerberos
Import-PSSession $exchSession
It looks like the ActiveDirectory module is not installed on that machine, you can install the MSFT RSAT tools to get it.
Try the following, It works!! {I tried after giving the Authentication type}
$pass = ConvertTo-SecureString -AsPlainText 'PASSWORD' -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList 'USERNAME',$pass
$s=New-PSSession SERVERNAME -Credential $MySecureCreds -Authentication Credssp
Invoke-Command -Session $s -scriptblock {
Get-CsUser User
}

How to add user in a Active directory Group using powershell

The code I have used to create user is:
Import-Module ActiveDirectory
$total = 2
for ($userIndex=0; $userIndex -lt $total; $userIndex++)
{
$userID = “{0:0000}” -f ($userIndex + 1)
$userName = “Super.admin$userID”
Write-Host “Creating user” ($userIndex + 1) “of” $total “:” $userName
New-ADUser `
-AccountPassword (ConvertTo-SecureString “admin#123” -AsPlainText -Force) `
-City “City” `
-Company “Company” `
-Country “US” `
-Department “Department” `
-Description (“TEST ACCOUNT ” + $userID + “: This user account does not represent a real user and is meant for test purposes only”)`
-DisplayName “Test User ($userID)” `
-Division “Division” `
-EmailAddress “$userName#DESMOSEDICI.local” `
-EmployeeNumber “$userID” `
-EmployeeID “ISED$userID” `
-Enabled $true `
-Fax “703-555-$userID” `
-GivenName “Test” `
-HomePhone “703-556-$userID” `
-Initials “TU$userID” `
-MobilePhone “703-557-$userID” `
-Name “Super.Admin ($userID)” `
-Office “Office: $userID”`
-OfficePhone “703-558-$userID” `
-Organization “Organization” `
-Path "OU=BusinessUnit,DC=Domain,DC=com" `
-POBox “PO Box $userID”`
-PostalCode $userID `
-SamAccountName $userName `
-State “VA – Virginia” `
-StreetAddress “$userID Any Street” `
-Surname “User ($userID)” `
-Title “Title” `
-UserPrincipalName “$userName#Domain.com“
}
Under my business unit group HR is created. How can I add a user in this group or create the users and assign the HR group to the users using the above script?
I tried to change the -Path
-Path "CN=HR,OU=Utility,DC=DESMOSEDICI,DC=com"
But it is not working.
Path is the Organizational Unit (or Container) the account will be created in. It has nothing to do with Group membership.
Use:
Add-ADGroupMember "CN=HR,OU=Utility,DC=DESMOSEDICI,DC=com" -Member "$userName#Domain.com"
Edit: This shows the command in the context of your script:
Import-Module ActiveDirectory
$total = 2
for ($userIndex=0; $userIndex -lt $total; $userIndex++) {
$userID = "{0:0000}" -f ($userIndex + 1)
$userName = "Super.admin$userID"
Write-Host "Creating user" ($userIndex + 1) "of" $total ":" $userName
New-ADUser `
-AccountPassword (ConvertTo-SecureString "admin#123" -AsPlainText -Force) `
-City "City" `
-Company "Company" `
-Country "US" `
-Department "Department" `
-Description ("TEST ACCOUNT " + $userID + ": This user account does not represent a real user and is meant for test purposes only")`
-DisplayName "Test User ($userID)" `
-Division "Division" `
-EmailAddress "$userName#DESMOSEDICI.local" `
-EmployeeNumber "$userID" `
-EmployeeID "ISED$userID" `
-Enabled $true `
-Fax "703-555-$userID" `
-GivenName "Test" `
-HomePhone "703-556-$userID" `
-Initials "TU$userID" `
-MobilePhone "703-557-$userID" `
-Name "Super.Admin ($userID)" `
-Office "Office: $userID"`
-OfficePhone "703-558-$userID" `
-Organization "Organization" `
-Path "OU=BusinessUnit,DC=Domain,DC=com" `
-POBox "PO Box $userID"`
-PostalCode $userID `
-SamAccountName $userName `
-State "VA – Virginia" `
-StreetAddress "$userID Any Street" `
-Surname "User ($userID)" `
-Title "Title" `
-UserPrincipalName "$userName#Domain.com"
Add-ADGroupMember "CN=HR,OU=Utility,DC=DESMOSEDICI,DC=com" -Member "$userName#Domain.com"
}
If you are receiving errors from New-ADUser something is wrong with your existing script, the new command is entirely separate and must fall after New-ADUser has done its job.

Create AD User using multiple input prompts

I want to create AD user by asking prompts from user input one by one.
I searched the script from google. See below.
$title = "Login"
$message = "Please enter your information to login!"
$name = New-Object System.Management.Automation.Host.FieldDescription "Name"
$name.Label = "&Login Name"
$name.DefaultValue = "Guest"
$pwd = New-Object System.Management.Automation.Host.FieldDescription "Password"
$pwd.Label = "&Password"
$pwd.SetparameterType( [System.Security.SecureString] )
$pwd.HelpMessage = "Please type your Password."
$fields = [System.Management.Automation.Host.FieldDescription[]]($name, $pwd)
$login=$Host.UI.Prompt($title, $message, $fields)
How to pass these parameters in below old statement
New-ADUser -Name “Charlie Russel” `
-AccountPassword "testing" `
-SamAccountName 'Charlie’ `
-DisplayName 'Charlie Russel’ `
-EmailAddress 'Charlie#TreyResearch.net’ `
-Enabled $True `
-GivenName 'Charlie’ `
-PassThru `
-PasswordNeverExpires $True `
-Surname 'Russel’ `
-UserPrincipalName 'Charlie’
You can access it using $login.Name and $login.Password:
New-ADUser -Name 'Charlie Russel' `
-AccountPassword $login.Password `
-SamAccountName $login.Name `
-DisplayName 'Charlie Russel’ `
-EmailAddress 'Charlie#TreyResearch.net’ `
-Enabled $True `
-GivenName 'Charlie’ `
-PassThru `
-PasswordNeverExpires $True `
-Surname 'Russel’ `
-UserPrincipalName 'Charlie'