Packer.Images/scripts/ADDS/payload/scripts/03.Users.ps1

69 lines
2.7 KiB
PowerShell

#Requires -Modules 'ActiveDirectory'
Param(
[Parameter(Mandatory)]
[hashtable]$Parameter
)
# Only executed on primary or standalone Domain Controller
If (@('primary','standalone') -contains $Parameter['deployment.type']) {
$GetContentSplat = @{
Path = "$($PSScriptRoot)\$($MyInvocation.MyCommand)".Replace('.ps1', ".yml")
Raw = $True
}
$RawContent = Get-Content @GetContentSplat
$ConvertFromYamlSplat = @{
Yaml = $RawContent
AllDocuments = $True
}
$YamlDocuments = ConvertFrom-Yaml @ConvertFromYamlSplat
# Check if the respective .yml file declared substitutions which need to be parsed
If (($YamlDocuments.Count -gt 1) -and $YamlDocuments[-1].Variables) {
ForEach ($Pattern in $YamlDocuments[-1].Variables) {
$RawContent = $RawContent -replace "\{\{ ($($Pattern.Name)) \}\}", [string](Invoke-Expression -Command $Pattern.Expression)
}
# Perform conversion to Yaml again, now with parsed file contents
$ConvertFromYamlSplat = @{
Yaml = $RawContent
AllDocuments = $True
}
$YamlDocuments = ConvertFrom-Yaml @ConvertFromYamlSplat
$Entries = $YamlDocuments[0..($YamlDocuments.Count - 2)]
}
Else {
$Entries = $YamlDocuments
}
ForEach ($User in $Entries.Users) {
$UserName = ($User.DistinguishedName -split ',', 2)[0].Substring(3)
$SanitizedUPN = ($UserName -replace "[^a-zA-Z0-9'\.-_!#\^~]").Trim('.')
# Create new user
$NewADUserSplat = @{
Name = $UserName
UserPrincipalName = "$($SanitizedUPN)@$((Get-ADDomain).DNSRoot)"
Path = ($User.DistinguishedName -split ',', 2)[1] + (',{0}' -f (Get-ADRootDSE).rootDomainNamingContext)
AccountPassword = ConvertTo-SecureString $User.Password -AsPlainText -Force
PassThru = $True
ErrorAction = 'SilentlyContinue'
}
$NewADUser = New-ADUser @NewADUserSplat
# Add user to group(s)
If ([boolean]$User.MemberOf) {
ForEach ($Group in $User.MemberOf) {
$AddADGroupMemberSplat = @{
Identity = $Group + (',{0}' -f (Get-ADRootDSE).rootDomainNamingContext)
Members = $NewADUser.DistinguishedName
ErrorAction = 'SilentlyContinue'
}
Add-ADGroupMember @AddADGroupMemberSplat
}
}
# Enable user
$EnableADAccountSplat = @{
Identity = $NewADUser.DistinguishedName
ErrorAction = 'Continue'
}
Enable-ADAccount @EnableADAccountSplat
}
}