'PowerShell Script User Account creation
I have this script to create my users at my Active Directory Forest:
In a quick overview:
- My script reads a source file with the accounts to upload
- I test the existance of the accounts to process
- We Process the accounts, and every account is logged to a Result file
- In the end, an email is sent to the admins and to my helpdesk with the result file and the log.
I have 3 controllers (S01, S02, S03) in a Forest (ctx.local) I run this script at S03. S02 runs my script to create users at my Office 365 tenant. S01 is the main controller.
My forest syncs with my Radius Server to give access to the users that I upload using this script. My users needs to be upload at the forest to have access to wifi resources.
This script is scheduled to run at the server at 8pm. with the highest levels, and with the domain admin account.
Import-Module ActiveDirectory
cls
$date = Get-Date
$fecha = $date.ToString("ddMMyyyy_HHmmss")
$pSourceFile = "C:\PowerShell\Data\ExportWIFI.csv"
#ARCHIVO DE RESULTADOS
$pResultFile = "C:\PowerShell\logs\Results_createusers_wifi_$($fecha).csv";
Function Test-ADUser {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,position=0)]
[string]$Username
)
Try {
Get-ADuser $Username -ErrorAction Stop
return $true
}
Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
return $false
}
}
$Users = Import-Csv -Delimiter ";" -Path $pSourceFile
$date = Get-Date
$inicio = $date.ToString("dd-MM-yyyy HH:mm:ss")
Add-Content -Path $pResultFile -Value "$(Get-Date) - PROCESAMIENTO DE CUENTAS PARA WIFI"
foreach ($User in $Users)
{
#write-output $User.Password
$Password = $User.Password
Add-Content -Path $pResultFile -Value "$(Get-Date) - Procesando Cuenta $($User.Username) - Clave $($Password)"
if (Test-ADUser -Username $User.Username)
{
Add-Content -Path $pResultFile -Value "$(Get-Date) - La cuenta $($User.Username) - $($User.DisplayName) ya existe!!!!"
}
else
{
try
{
New-ADUser `
-Name $User.DisplayName `
-DisplayName $User.DisplayName `
-EmailAddress $User.emailaddress `
-GivenName $User.FirstName `
-SamAccountName $User.Username `
-Surname $User.SurName `
-UserPrincipalName $User.Username `
-AccountPassword (ConvertTo-SecureString $Password -AsPlainText -force) `
-Enabled 1 `
-PasswordNeverExpires 1 `
-PassThru `
-Path "OU=2018,DC=ctx,DC=local"
Add-Content -Path $pResultFile -Value "$(Get-Date) - La cuenta $($User.Username) - $($User.DisplayName) registrada exitosamente!!!!"
}
catch
{
$ErrorMsg = $_.Exception.Message
Add-Content -Path $pResultFile -Value "$(Get-Date) Error al procesar cuenta $($user.DisplayName) <$($user.Username)> con el Error [$($ErrorMsg)]"
}
}
}
#FIN DE LA RUTINA
$date = Get-Date
$fin = $date.ToString("dd-MM-yyyy HH:mm:ss")
Add-Content -Path $pResultFile -Value "$(Get-Date) PROCESAMIENTO DE CUENTAS CULMINADO"
$ToAdmins = @('[email protected]', '[email protected]', '[email protected]')
$Subject="PROCESAMIENTO DE CREACION DE CUENTAS PARA WIFI CTXDOM - $(Get-Date)"
$EmailBody = @"
<html>
<head>
</head>
<body>
<p align='center'>
<img src='data:' alt='' border='0'>
</p>
<p align='center'>
<H1><b>PROCESAMIENTO DE CUENTAS DE WIFI</b></H1>
<hr/>
<p align='justify'>Adjunto bitacora y resultado del procesamiento de cuentas para el acceso al WIFI iniciada el $inicio y culminada el $fin .</p>
<hr/>
</body><br />
</html><br />
"@
$Adjuntos=@("$($pResultFile)", "$($pSourceFile)")
#Enviamos la bitacora
Send-MailMessage -SMTPServer 172.16.8.103 -To $ToAdmins -From [email protected] -Subject $Subject -Body $EmailBody -BodyAsHtml -Attachments $Adjuntos
So, long story short, my issue here is this, when I run the script, at the New-Aduser cmdlet Even if I specify the -Enabled 1 so my accounts are enabled when they are created, my accounts are not enabled. They area created in a disabled state.
Running manually my script I'm getting this in my log:
04/27/2022 11:14:03 - PROCESAMIENTO DE CUENTAS PARA WIFI
04/27/2022 11:14:03 - Procesando Cuenta -------- - Clave --------
04/27/2022 11:14:03 - La cuenta -------- - ----------- ya existe!!!!
04/27/2022 11:14:03 - Procesando Cuenta rquirosc - Clave ******
04/27/2022 11:14:03 - La cuenta rquirosc - Rolando A. Quiros C. ya existe!!!!
04/27/2022 11:14:03 - Procesando Cuenta tlight - Clave *******
04/27/2022 11:14:04 Error al procesar cuenta Thomas X. Light <tlight> con el Error [Acceso denegado] (Here Error procesing account Thomas X. Light <tlight> with Error [Access Denied]
04/27/2022 11:14:04 PROCESAMIENTO DE CUENTAS CULMINADO
So If I run an Enable-ADAccount command, I receive this stating that I have "Insufficient Rights", even using the domain admin account to do this job:
PS C:\Users\admind> Enable-ADAccount -identity tlight
Enable-ADAccount : Los derechos de acceso son insuficientes para realizar la operación
En línea: 1 Carácter: 1
+ Enable-ADAccount -identity tlight
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (tlight:ADAccount) [Enable-ADAccount], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8344,Microsoft.ActiveDirectory.Management.Commands.EnableADAccount
PS C:\Users\admind>
What am I missing? What am I doing wrong?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
