87 lines
2.4 KiB
PowerShell
87 lines
2.4 KiB
PowerShell
param(
|
|
[Parameter(Mandatory=$true)]
|
|
[string]$InputFile
|
|
)
|
|
|
|
# Read input JSON
|
|
try {
|
|
$json = Get-Content -Raw -Path $InputFile -ErrorAction Stop
|
|
$payload = $json | ConvertFrom-Json
|
|
} catch {
|
|
$err = $_.Exception.Message
|
|
Write-Output (@{ success = $false; message = "Failed to read/parse input JSON: $err" } | ConvertTo-Json -Compress)
|
|
exit 1
|
|
}
|
|
|
|
# Default result
|
|
$result = @{ success = $false; message = "Unspecified error" }
|
|
|
|
# Validate
|
|
if (-not $payload.samaccountname -or -not $payload.password) {
|
|
$result.message = "Required fields: samaccountname and password"
|
|
Write-Output ($result | ConvertTo-Json -Compress)
|
|
exit 1
|
|
}
|
|
|
|
# Convert to strings
|
|
$sam = [string]$payload.samaccountname
|
|
$display = [string]($payload.displayname)
|
|
$mail = [string]($payload.mail)
|
|
$pass = [string]$payload.password
|
|
$ou = [string]($payload.ou)
|
|
$groups = [string]($payload.groups)
|
|
$dryRun = [bool]($payload.dry_run -as [bool])
|
|
|
|
# Ensure ActiveDirectory module available
|
|
try {
|
|
Import-Module ActiveDirectory -ErrorAction Stop
|
|
} catch {
|
|
$result.message = "ActiveDirectory PowerShell module not available: $($_.Exception.Message)"
|
|
Write-Output ($result | ConvertTo-Json -Compress)
|
|
exit 1
|
|
}
|
|
|
|
# Build New-ADUser parameters
|
|
$props = @{
|
|
Name = if ($display -and $display -ne '') { $display } else { $sam }
|
|
SamAccountName = $sam
|
|
Enabled = $true
|
|
}
|
|
|
|
if ($mail -and $mail -ne '') { $props['EmailAddress'] = $mail }
|
|
if ($ou -and $ou -ne '') { $props['Path'] = $ou }
|
|
|
|
# Build secure password
|
|
$securePass = ConvertTo-SecureString $pass -AsPlainText -Force
|
|
$props['AccountPassword'] = $securePass
|
|
|
|
# Execute
|
|
if ($dryRun) {
|
|
$result.success = $true
|
|
$result.message = "DRY RUN: would create user $sam"
|
|
Write-Output ($result | ConvertTo-Json -Compress)
|
|
exit 0
|
|
}
|
|
|
|
try {
|
|
# Create the AD user
|
|
New-ADUser @props -ErrorAction Stop
|
|
|
|
# Add to groups, if provided
|
|
if ($groups -and $groups -ne '') {
|
|
$groupList = $groups -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }
|
|
foreach ($g in $groupList) {
|
|
Add-ADGroupMember -Identity $g -Members $sam -ErrorAction Stop
|
|
}
|
|
}
|
|
|
|
$result.success = $true
|
|
$result.message = "User $sam created successfully"
|
|
Write-Output ($result | ConvertTo-Json -Compress)
|
|
exit 0
|
|
} catch {
|
|
$result.message = "Error creating user $sam: $($_.Exception.Message)"
|
|
Write-Output ($result | ConvertTo-Json -Compress)
|
|
exit 1
|
|
}
|