Skip to content

Instantly share code, notes, and snippets.

@josephsindel
Created November 21, 2017 23:39
Show Gist options
  • Save josephsindel/96f7405a8596d3100840091b600a45e7 to your computer and use it in GitHub Desktop.
Save josephsindel/96f7405a8596d3100840091b600a45e7 to your computer and use it in GitHub Desktop.
for joeSin
# Example PowerShell script to domain join a Windows instance securely
$ErrorActionPreference = 'Stop'
try{
# Parameter names
$DomainDNS = DomainDNSRecord
$DomainName = DomainName
$DomainJoinUserName = AccountName
$DomainJoinPassword = DomainJoinPassword
$DomainJoinOU = DomainJoinOU
# Retrieve configuration values from parameters
$ipDomainDNS = (Get-SSMParameterValue -Name $DomainDNS).Parameters[0].Value
$domain = (Get-SSMParameterValue -Name $domainName).Parameters[0].Value
$OU = (Get-SSMParameterValue -Name $domainJoinOU).Parameters[0].Value
$username = $domain + '\' + (Get-SSMParameterValue -Name $domainJoinUserName).Parameters[0].Value
$passparam = (Get-SSMParameterValue -Name $DomainJoinPassword WithDecryption $True).Parameters[0].Value
$password = ConvertTo-SecureString -string $passparam -AsPlainText -Force
# Create a System.Management.Automation.PSCredential object
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
# Determine the name of the Network Adapter of this machine
$networkAdapter = Get-WmiObject Win32_NetworkAdapter -Filter "AdapterType= 'Ethernet 802.3'"
$networkAdapterName = ($networkAdapter | Select-Object -First 1).NetConnectionID
# Set up the IPv4 address of the AD DomainDNS server as the first DomainDNS server on this machine
netsh.exe interface ipv4 add DomainDNSservers name="$networkAdapterName" address=$ipDomainDNS index=1
$instanceId = (New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
############ Make sure and change hardcoded region.
$Tag_Hostname = Get-EC2Tag -region eu-central-1 | Where-Object {$_.ResourceId -eq $instanceId -and $_.Key -eq 'Hostname'}
$newcomputername = $Tag_Hostname.value
Rename-Computer -NewName $newcomputername
sleep 5
add-computer -DomainName $domain -Credential $Credential -OUPath $OU -force -Options JoinWithNewName,AccountCreate -restart}
catch [Exception]{
Write-Host $_.Exception.ToString()
Write-Host 'Command execution failed.'
$host.SetShouldExit(1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment