automacao-identidade-ad/scripts/cria-usuario-unico.ps1

385 lines
21 KiB
PowerShell

<#
.SYNOPSIS
Cria um novo usuário no Active Directory com um conjunto completo de atributos e habilita sua caixa de correio no Exchange.
.DESCRIPTION
Versão 2.0 do script de provisionamento. Desenvolvido para o projeto "Plataforma Unificada de Trabalho Digital", esta ferramenta robusta
suporta a criação de usuários com mais de 25 atributos comuns do AD, com validações críticas para garantir a integridade dos dados.
O script é projetado para automação e não permite interação via console.
.NOTES
Autor: Gemini (Especialista NGINX & Automação)
Data: 14 de outubro de 2025
Versão: 2.0 - Expansão massiva de atributos, campos obrigatórios e validação dupla de unicidade (SamAccountName e UserPrincipalName).
Contexto: Projeto Plataforma Unificada de Trabalho Digital
#>
[CmdletBinding(DefaultParameterSetName = 'SingleUser')]
param(
# --- Parâmetros de Conexão e Autenticação (Obrigatórios para todas as operações) ---
[Parameter(Mandatory = $true, Position = 0)]
[string]$ClientADServer,
[Parameter(Mandatory = $true, Position = 1)]
[pscredential]$ClientADCredential,
[Parameter(Mandatory = $true, Position = 2)]
[string]$ExchangeADServer,
[Parameter(Mandatory = $true, Position = 3)]
[pscredential]$ExchangeADCredential,
# --- Parâmetros de Input (Escolha um método) ---
[Parameter(Mandatory = $true, ParameterSetName = 'CsvImport')]
[string]$CsvPath,
[Parameter(Mandatory = $true, ParameterSetName = 'DbImport')]
[switch]$FromDatabase,
# --- ATRIBUTOS CRÍTICOS (Obrigatórios para criação de usuário único) ---
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$SamAccountName,
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$UserPrincipalName,
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$GivenName,
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$Surname,
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$Name,
[Parameter(Mandatory = $true, ParameterSetName = 'SingleUser')]
[string]$Path,
# --- ATRIBUTOS OPCIONAIS ---
# -- Organização --
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Title,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Department,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Company,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Manager,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$EmployeeID,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$EmployeeNumber,
# -- Contato --
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$OfficePhone,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$MobilePhone,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$EmailAddress,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$StreetAddress,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$City,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$State,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$PostalCode,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Country,
# -- Perfil --
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Description,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$Office,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$HomePage,
# -- Controle da Conta --
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [switch]$PasswordNeverExpires,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [switch]$CannotChangePassword,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [datetime]$AccountExpirationDate,
# -- Atributos Customizados --
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$extensionAttribute1,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$extensionAttribute2,
[Parameter(Mandatory = $false, ParameterSetName = 'SingleUser')] [string]$ProxyAddresses,
# --- Parâmetros de Logging ---
[Parameter(Mandatory = $false)] [string]$DatabaseConnectionString,
[Parameter(Mandatory = $false)] [string]$LogFilePath = ".\New-UnifiedADUser-Log-$(Get-Date -Format 'yyyy-MM-dd').txt"
)
# --- FUNÇÕES AUXILIARES ---
function Write-Log {
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[Parameter(Mandatory = $true)]
[ValidateSet('INFO', 'WARN', 'ERROR')]
[string]$Level,
[Parameter(Mandatory = $false)]
[string]$TargetADServer
)
$logEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - [$Level] - $Message"
$scriptUser = $env:USERNAME
try {
if (-not [string]::IsNullOrEmpty($DatabaseConnectionString)) {
# [PLACEHOLDER] Lógica de log no banco de dados.
Write-Verbose "Log enviado para o banco de dados."
}
}
catch {
$dbErrorMessage = "Falha ao gravar no banco de dados: $($_.Exception.Message)"
"$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - [ERROR] - $dbErrorMessage" | Out-File -FilePath $LogFilePath -Append
}
$logEntry | Out-File -FilePath $LogFilePath -Append
if (-not [string]::IsNullOrEmpty($TargetADServer)) {
try {
$eventMessage = "Script 'New-UnifiedADUser.ps1' executado por '$scriptUser'.`nDetalhes: $Message"
$eventLevel = switch ($Level) {
'INFO' { 'Information' }
'WARN' { 'Warning' }
'ERROR' { 'Error' }
}
Invoke-Command -ComputerName $TargetADServer -ScriptBlock {
param($eventMessage, $eventLevel)
$logSource = "Provisionamento de Usuários AD"
if (-not ([System.Diagnostics.EventLog]::SourceExists($logSource))) {
New-EventLog -LogName 'Application' -Source $logSource
}
Write-EventLog -LogName 'Application' -Source $logSource -EventId 1001 -EntryType $eventLevel -Message $eventMessage
} -ArgumentList $eventMessage, $eventLevel
Write-Verbose "Log de evento escrito em '$TargetADServer'."
}
catch {
$eventErrorMessage = "Falha ao escrever no Event Log de '$TargetADServer': $($_.Exception.Message)"
"$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - [ERROR] - $eventErrorMessage" | Out-File -FilePath $LogFilePath -Append
}
}
}
function Show-Usage {
Write-Host @"
ERRO: O script foi chamado sem os parâmetros necessários ou com um método de entrada de dados inválido.
Este script cria usuários no AD do cliente e no AD do Exchange e deve ser chamado com todos os parâmetros requeridos.
MÉTODOS DE USO:
1. Criação de Usuário Único (parâmetros diretos):
Forneça os dados do usuário via parâmetros na linha de comando.
Exemplo:
.\New-UnifiedADUser.ps1 -SamAccountName 'joao.silva' -GivenName 'João' -Surname 'Silva' -Name 'João da Silva' `
-UserPrincipalName 'joao.silva@cliente.com.br' -Path 'OU=Usuarios,DC=local' `
-Title 'Analista' -Department 'TI' `
-ClientADServer '...' -ClientADCredential (Get-Credential) -ExchangeADServer '...' -ExchangeADCredential (Get-Credential)
2. Criação em Massa via CSV (usando o parâmetro -CsvPath):
Forneça um arquivo CSV com os dados de todos os usuários.
Exemplo:
.\New-UnifiedADUser.ps1 -CsvPath 'C:\temp\usuarios.csv' -ClientADServer '...' -ClientADCredential (Get-Credential) -ExchangeADServer '...' -ExchangeADCredential (Get-Credential)
"@
}
# --- LÓGICA PRINCIPAL ---
if ($PSBoundParameters.Count -eq 0) {
Show-Usage
exit 1
}
try {
Import-Module ActiveDirectory -ErrorAction Stop
}
catch {
Write-Log -Level 'ERROR' -Message "Falha ao importar o módulo ActiveDirectory. Verifique se as Ferramentas de Administração de Servidor Remoto (RSAT) estão instaladas."
exit 1
}
Write-Host "Coletando informações da floresta de AD para validação..."
try {
$adForest = Get-ADForest -Server $ClientADServer -Credential $ClientADCredential
[array]$validUPNSuffixes = $adForest.UPNSuffixes + $adForest.RootDomain
Write-Log -Level 'INFO' -Message "Sufixos de UPN válidos carregados: $($validUPNSuffixes -join ', ')"
}
catch {
Write-Log -Level 'ERROR' -Message "Não foi possível obter informações da floresta do AD. Verifique a conexão e as credenciais. Erro: $($_.Exception.Message)"
exit 1
}
$usersToProcess = @()
switch ($PSCmdlet.ParameterSetName) {
'SingleUser' {
$usersToProcess += [PSCustomObject]@{
SamAccountName = $SamAccountName; UserPrincipalName = $UserPrincipalName; GivenName = $GivenName; Surname = $Surname; Name = $Name; Path = $Path; Title = $Title; Department = $Department; Company = $Company; Manager = $Manager; EmployeeID = $EmployeeID; EmployeeNumber = $EmployeeNumber; OfficePhone = $OfficePhone; MobilePhone = $MobilePhone; EmailAddress = $EmailAddress; StreetAddress = $StreetAddress; City = $City; State = $State; PostalCode = $PostalCode; Country = $Country; Description = $Description; Office = $Office; HomePage = $HomePage; PasswordNeverExpires = $PasswordNeverExpires; CannotChangePassword = $CannotChangePassword; AccountExpirationDate = $AccountExpirationDate; extensionAttribute1 = $extensionAttribute1; extensionAttribute2 = $extensionAttribute2; ProxyAddresses = $ProxyAddresses
}
break
}
'CsvImport' {
try {
$usersToProcess = Import-Csv -Path $CsvPath -ErrorAction Stop
Write-Log -Level 'INFO' -Message "Arquivo CSV '$CsvPath' carregado com $($usersToProcess.Count) registros."
}
catch {
Write-Log -Level 'ERROR' -Message "Não foi possível ler o arquivo CSV em '$CsvPath'. Erro: $($_.Exception.Message)"
exit 1
}
break
}
'DbImport' {
Write-Log -Level 'WARN' -Message "O método de importação via banco de dados (-FromDatabase) ainda não foi implementado."
exit 1
break
}
default {
Show-Usage
exit 1
}
}
foreach ($user in $usersToProcess) {
Write-Host "Iniciando processamento para o usuário: $($user.SamAccountName)"
Write-Log -Level 'INFO' -Message "Iniciando provisionamento para o usuário '$($user.SamAccountName)'."
# --- BLOCO DE VALIDAÇÕES APRIMORADO ---
$validationFailed = $false
# 1. Validação de Campos Críticos Obrigatórios
$mandatoryFields = @('SamAccountName', 'UserPrincipalName', 'GivenName', 'Surname', 'Name', 'Path')
foreach ($field in $mandatoryFields) {
if ([string]::IsNullOrWhiteSpace($user.$field)) {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: O campo crítico obrigatório '$field' está faltando para '$($user.SamAccountName)'."
$validationFailed = $true
break
}
}
if ($validationFailed) { Write-Host " [ERRO] Falha na validação de campos obrigatórios." -ForegroundColor Red; continue }
# 2. Validação de Unicidade (SamAccountName e UserPrincipalName)
if (Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'" -Server $ClientADServer -Credential $ClientADCredential) {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: O SamAccountName '$($user.SamAccountName)' já existe."
$validationFailed = $true
}
if (Get-ADUser -Filter "UserPrincipalName -eq '$($user.UserPrincipalName)'" -Server $ClientADServer -Credential $ClientADCredential) {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: O UserPrincipalName '$($user.UserPrincipalName)' já existe."
$validationFailed = $true
}
# 3. Validação de OU
if (-not (Get-ADOrganizationalUnit -Filter "DistinguishedName -eq '$($user.Path)'" -Server $ClientADServer -Credential $ClientADCredential)) {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: A OU '$($user.Path)' não foi encontrada no Active Directory."
$validationFailed = $true
}
# 4. Validação de UPN
$upnSuffix = ($user.UserPrincipalName).Split('@')[1]
if ($upnSuffix -eq 'exch.local') {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: O UPN '$($user.UserPrincipalName)' usa o sufixo proibido 'exch.local'."
$validationFailed = $true
}
elseif ($validUPNSuffixes -notcontains $upnSuffix) {
Write-Log -Level 'ERROR' -Message "USUÁRIO IGNORADO: O sufixo de UPN '@$upnSuffix' não é válido para esta floresta."
$validationFailed = $true
}
if ($validationFailed) { Write-Host " [ERRO] Falha na validação. Verifique o log para detalhes." -ForegroundColor Red; continue }
# --- FIM DAS VALIDAÇÕES ---
$clientADSuccess = $false
try {
$tempPassword = -join ((65..90) + (97..122) + (48..57) | Get-Random -Count 16 | ForEach-Object { [char]$_ })
$securePassword = ConvertTo-SecureString $tempPassword -AsPlainText -Force
# Inicia a construção dos parâmetros para o New-ADUser
$userParams = @{
SamAccountName = $user.SamAccountName
UserPrincipalName = $user.UserPrincipalName
GivenName = $user.GivenName
Surname = $user.Surname
Name = $user.Name
DisplayName = $user.Name
Path = $user.Path
AccountPassword = $securePassword
Enabled = $true
ChangePasswordAtLogon = $true
}
# --- ADIÇÃO CONDICIONAL DE TODOS OS ATRIBUTOS OPCIONAIS ---
# A checagem '... -contains ...' garante que o script não falhe se a coluna não existir no CSV
if ($user.PSObject.Properties.Name -contains 'EmailAddress' -and -not [string]::IsNullOrWhiteSpace($user.EmailAddress)) { $userParams.Add('EmailAddress', $user.EmailAddress) }
if ($user.PSObject.Properties.Name -contains 'Description' -and -not [string]::IsNullOrWhiteSpace($user.Description)) { $userParams.Add('Description', $user.Description) }
# Organização
if ($user.PSObject.Properties.Name -contains 'Title' -and -not [string]::IsNullOrWhiteSpace($user.Title)) { $userParams.Add('Title', $user.Title) }
if ($user.PSObject.Properties.Name -contains 'Department' -and -not [string]::IsNullOrWhiteSpace($user.Department)) { $userParams.Add('Department', $user.Department) }
if ($user.PSObject.Properties.Name -contains 'Company' -and -not [string]::IsNullOrWhiteSpace($user.Company)) { $userParams.Add('Company', $user.Company) }
if ($user.PSObject.Properties.Name -contains 'EmployeeID' -and -not [string]::IsNullOrWhiteSpace($user.EmployeeID)) { $userParams.Add('EmployeeID', $user.EmployeeID) }
if ($user.PSObject.Properties.Name -contains 'EmployeeNumber' -and -not [string]::IsNullOrWhiteSpace($user.EmployeeNumber)) { $userParams.Add('EmployeeNumber', $user.EmployeeNumber) }
if ($user.PSObject.Properties.Name -contains 'Office' -and -not [string]::IsNullOrWhiteSpace($user.Office)) { $userParams.Add('physicalDeliveryOfficeName', $user.Office) }
# Contato
if ($user.PSObject.Properties.Name -contains 'OfficePhone' -and -not [string]::IsNullOrWhiteSpace($user.OfficePhone)) { $userParams.Add('OfficePhone', $user.OfficePhone) }
if ($user.PSObject.Properties.Name -contains 'MobilePhone' -and -not [string]::IsNullOrWhiteSpace($user.MobilePhone)) { $userParams.Add('Mobile', $user.MobilePhone) }
# Endereço
if ($user.PSObject.Properties.Name -contains 'StreetAddress' -and -not [string]::IsNullOrWhiteSpace($user.StreetAddress)) { $userParams.Add('StreetAddress', $user.StreetAddress) }
if ($user.PSObject.Properties.Name -contains 'City' -and -not [string]::IsNullOrWhiteSpace($user.City)) { $userParams.Add('City', $user.City) }
if ($user.PSObject.Properties.Name -contains 'State' -and -not [string]::IsNullOrWhiteSpace($user.State)) { $userParams.Add('State', $user.State) }
if ($user.PSObject.Properties.Name -contains 'PostalCode' -and -not [string]::IsNullOrWhiteSpace($user.PostalCode)) { $userParams.Add('PostalCode', $user.PostalCode) }
if ($user.PSObject.Properties.Name -contains 'Country' -and -not [string]::IsNullOrWhiteSpace($user.Country)) { $userParams.Add('Country', $user.Country) }
# Perfil Web
if ($user.PSObject.Properties.Name -contains 'HomePage' -and -not [string]::IsNullOrWhiteSpace($user.HomePage)) { $userParams.Add('HomePage', $user.HomePage) }
# Controle da Conta
if ($user.PSObject.Properties.Name -contains 'AccountExpirationDate' -and $user.AccountExpirationDate) { $userParams.Add('AccountExpirationDate', ([datetime]$user.AccountExpirationDate)) }
if ($user.PSObject.Properties.Name -contains 'PasswordNeverExpires' -and ($user.PasswordNeverExpires -eq 'True' -or $user.PasswordNeverExpires -is [bool] -and $user.PasswordNeverExpires)) { $userParams.Add('PasswordNeverExpires', $true) }
if ($user.PSObject.Properties.Name -contains 'CannotChangePassword' -and ($user.CannotChangePassword -eq 'True' -or $user.CannotChangePassword -is [bool] -and $user.CannotChangePassword)) { $userParams.Add('CannotChangePassword', $true) }
# Atributos Customizados
if ($user.PSObject.Properties.Name -contains 'extensionAttribute1' -and -not [string]::IsNullOrWhiteSpace($user.extensionAttribute1)) { $userParams.Add('extensionAttribute1', $user.extensionAttribute1) }
if ($user.PSObject.Properties.Name -contains 'extensionAttribute2' -and -not [string]::IsNullOrWhiteSpace($user.extensionAttribute2)) { $userParams.Add('extensionAttribute2', $user.extensionAttribute2) }
# Lógica para Múltiplos E-mails (ProxyAddresses)
if ($user.PSObject.Properties.Name -contains 'ProxyAddresses' -and -not [string]::IsNullOrWhiteSpace($user.ProxyAddresses)) {
$proxyList = @("SMTP:" + $user.UserPrincipalName)
$aliases = $user.ProxyAddresses -split ';'
foreach ($alias in $aliases) { if (-not [string]::IsNullOrWhiteSpace($alias)) { $proxyList += "smtp:" + $alias.Trim() } }
$userParams.Add('ProxyAddresses', $proxyList)
}
# Lógica para Gestor (Manager)
if ($user.PSObject.Properties.Name -contains 'Manager' -and -not [string]::IsNullOrWhiteSpace($user.Manager)) {
$managerUser = Get-ADUser -Filter "SamAccountName -eq '$($user.Manager)'" -Server $ClientADServer -Credential $ClientADCredential
if ($managerUser) {
$userParams.Add('Manager', $managerUser.DistinguishedName)
} else {
Write-Log -Level 'WARN' -Message "Gestor '$($user.Manager)' não encontrado para o usuário '$($user.SamAccountName)'. O campo não será preenchido."
}
}
# Criação do usuário no AD
New-ADUser @userParams -Server $ClientADServer -Credential $ClientADCredential -ErrorAction Stop
Write-Log -Level 'INFO' -Message "SUCESSO: Conta '$($user.SamAccountName)' criada no AD do Cliente. Senha temporária gerada." -TargetADServer $ClientADServer
Write-Host " [OK] Conta criada no AD do Cliente." -ForegroundColor Green
Write-Log -Level 'INFO' -Message "Senha temporária para '$($user.SamAccountName)': $tempPassword"
$clientADSuccess = $true
}
catch {
$errorMessage = "FALHA ao criar a conta '$($user.SamAccountName)' no AD do Cliente. Erro: $($_.Exception.Message -replace "`r`n"," ")"
Write-Log -Level 'ERROR' -Message $errorMessage -TargetADServer $ClientADServer
Write-Host " [ERRO] Falha ao criar no AD do Cliente." -ForegroundColor Red
continue
}
if ($clientADSuccess) {
try {
Start-Sleep -Seconds 5
Write-Log -Level 'INFO' -Message "Tentando habilitar a mailbox para '$($user.SamAccountName)' no AD do Exchange em '$ExchangeADServer'." -TargetADServer $ExchangeADServer
Enable-Mailbox -Identity $user.SamAccountName -DomainController $ExchangeADServer -Credential $ExchangeADCredential -ErrorAction Stop
Write-Log -Level 'INFO' -Message "SUCESSO: Mailbox para '$($user.SamAccountName)' habilitada no ambiente Exchange." -TargetADServer $ExchangeADServer
Write-Host " [OK] Mailbox habilitada no Exchange." -ForegroundColor Green
Write-Log -Level 'INFO' -Message "PROVISIONAMENTO COMPLETO para o usuário '$($user.SamAccountName)'."
}
catch {
$errorMessage = "FALHA PARCIAL: A conta '$($user.SamAccountName)' foi criada no AD do Cliente, mas falhou ao habilitar a mailbox no Exchange. Erro: $($_.Exception.Message -replace "`r`n"," ")"
Write-Log -Level 'ERROR' -Message $errorMessage -TargetADServer $ExchangeADServer
Write-Host " [ERRO] Falha ao habilitar a mailbox no Exchange." -ForegroundColor Red
}
}
}
Write-Host "Processamento concluído."