######################################################################################################
############################################### Steps ################################################
######################################################################################################
#
# Example:	
# .\JoinToDomain.ps1 -DomainName manageengine.com -DomainController manageengine-dc1 -DomainUsername admp -DomainUserPassword Test@123 -ComputerNetbios work-comp -ComputerUsername administrator -ComputerPassword Test@123
# 
# Parameters:
# - DomainName: Required
# - DomainController: Required , Domain Controller Netbios name
# - DomainUsername: Required , SAMAccountName of user with Admin Previleges
# - DomainUserPassword: Required, Password of the User
# - ComputerNetbios: Required, Netbios name of Workgroup computer
# - ComputerUsername: Required, 'administrator'
# - ComputerPassword: Required, Password for administrator of Workgroup computer
# - OU: Optional, Specify the FQDN of the Container to place the Workgroup computer object in Active Directory
# 
# Note:
# The Workgroup computer restarts after the successful completion of the script. To stop automatic reboot,remove the '/reboot' in $command.
# 
######################################################################################################

# Script Begins
# Parameters
param(
	[string] $DomainName,
	[string] $DomainController,
	[string] $DomainUsername,
	[string] $DomainUserPassword,
	[string] $ComputerNetbios,
	[string] $ComputerUsername,
	[string] $ComputerPassword,
	[string] $OU
)

$secureDomainUserPassword = $DomainUserPassword | ConvertTo-SecureString -asPlainText -Force 

# Create PS Credential Object
$dUsername = $DomainName + "\" + $DomainUsername
$domainCred = New-Object System.Management.Automation.PSCredential($dUsername,$secureDomainUserPassword)

# Netdom command
# Refer Doc: https://technet.microsoft.com/en-in/library/cc781853(v=ws.10).aspx
$command = "Netdom JOIN $ComputerNetbios /d:$DomainName /ud:$dUsername /pd:$DomainUserPassword /uo:$ComputerUsername /po:$ComputerPassword /ou:`"$OU`" /reboot"

# Invoke-Command -Computer (DC Name) -ScriptBlock { (Script to Execute) } -Credential (Domain Admin Credentials) -ArgumentList (Named Parameters to Pass)
$result = Invoke-Command -Computer $DomainController -ScriptBlock { iex $args[0] } -Credential $domainCred -ArgumentList (,$command)
$result
