$ScriptVersion = "1.0 - 6/15/2018 - Florian Rossmark
Clear-Host
Write-Host ""
Write-Host ""
Write-Host "Welcome to the Execute Domain-Join script"
Write-Host "========================================="
Write-Host ""
Write-Host ""
Write-Host "This script will do the following Steps:"
Write-Host "----------------------------------------"
Write-Host "- You enter the Computer Name / Host Name"
Write-Host "- You enter Domain Admin credentials for a Domain-Join"
Write-Host "- You enter credentials to access KeyPass Password server"
Write-Host ""
Write-Host ""
Write-Host "Note: always type credentials without any domain-information (MYDOMAIN\) - the script will fail otherwise."
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host "- The script will automatically create a KeyPass entry with all information"
Write-Host "- The script will automatically create a specific local admin account for this machine"
Write-Host "- The script will automatically rename the system to the given name"
Write-Host "- The script will automatically join the system to the domain"
Write-Host ""
Write-Host ""
Write-Host "Script Version: $ScriptVersion"
Write-Host ""
Write-Host ""
pause
#Upper area holds functions..
Function MakeUp-String([Int]$Size = 8, [Char[]]$CharSets = "ULNS", [Char[]]$Exclude) {
$Chars = @(); $TokenSet = @()
If (!$TokenSets) {$Global:TokenSets = @{
U = [Char[]]'ABCDEFGHJKLMNPQRSTUVWXYZ' #Upper case
L = [Char[]]'abcdefghijkmnpqrstuvwxyz' #Lower case
N = [Char[]]'23456789' #Numerals
S = [Char[]]'!@$!@$!@$!@$' #Symbols
}}
$CharSets | ForEach {
$Tokens = $TokenSets."$_" | ForEach {If ($Exclude -cNotContains $_) {$_}}
If ($Tokens) {
$TokensSet += $Tokens
If ($_ -cle [Char]"Z") {$Chars += $Tokens | Get-Random} #Character sets defined in upper case are mandatory
}
}
While ($Chars.Count -lt $Size) {$Chars += $TokensSet | Get-Random}
($Chars | Sort-Object {Get-Random}) -Join "" #Mix the (mandatory) characters and output string
};
#bypass/avoid certificate issues
Add-Type @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public class ServerCertificateValidationCallback
{
public static void Ignore()
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate
(
Object obj,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors
)
{
return true;
};
}
}
"@
[ServerCertificateValidationCallback]::Ignore();
#Script starts here...
Clear-Host
Write-Host ""
Write-Host ""
Write-Host "This script must be executed in a PowerShell with elevated rights!"
Write-Host ""
Write-Host ""
Write-Host "Stop the script with: CTRL + C any time..."
Write-Host ""
Write-Host ""
pause
Clear-Host
$ComputerName = Read-Host "Please enter the new Computer Name"
$DomainJoinCredentials = Get-Credential -Message "Enter your credentials for the domain join"
$KeePassCredentials = Get-Credential -Message “Enter your credentials to access Keepass Server”
$localAdminUser = $("$ComputerName" + "_Admin")
$PW = MakeUp-String(12)
$PWencrypted = ConvertTo-SecureString $PW -AsPlainText -Force
Clear-Host
Write-Host ""
Write-Host ""
Write-Host "Checking KeePass to see if those credentials already exist"
Write-Host ""
Write-Host ""
#Collecting MACs
$colMACItems = get-wmiobject Win32_NetworkAdapter | Where-Object {$_.MACAddress -like "*:*"}
foreach ($objMACItem in $colMACItems) {
$MACobj = $objMACItem |select Description,MACAddress
$MACs += $MACobj.MACAddress + " - " + $MACobj.Description + "
"
}
#Collecting SN/ServiceTag and HW information
$SN = "ServiceTag / SN: "+(Get-WmiObject win32_bios | select SerialNumber).SerialNumber
$Model = "Model: "+(Get-WmiObject win32_computersystem | select Model).Model
$Manufacturer = "Manufacturer: "+(Get-WmiObject win32_computersystem | select Manufacturer).Manufacturer
$UEFIKey = wmic path softwarelicensingservice get OA3xOriginalProductKey
$KeepassURL = "https://passwordserver.mydomain.local:10001"
$PWFolder = "Local Admin Accounts"
$PWName = "Individual Admin Account on $ComputerName"
$PWUser = $localAdminUser
$PWPassword = $PW
$PWDescription = "Hardware information:
=====================
$Manufacturer
$Model
$SN
UEFI BIOS Windows Key:
======================
$UEFIKey
Known MAC Addresses:
====================
$MACs
(MACs might be subject to change with Docking-Stations)"
$tokenParams = @{
grant_type='password';
username=$KeePassCredentials.UserName;
password=$KeePassCredentials.GetNetworkCredential().password;}
$JSON = Invoke-WebRequest -Uri "$KeepassURL/OAuth2/Token" -Method POST -Body $tokenParams -ContentType "application/x-www-form-urlencoded"
$Token = (ConvertFrom-Json $JSON.Content).access_token
$headers = @{
"Accept" = "application/json"
"Authorization" = "$Token"}
$GroupSearch = @{“search” = $PWFolder}
$Group = Invoke-RestMethod -Method post -Uri "$KeepassURL/api/v4/rest/search"-body (ConvertTo-Json $GroupSearch) -Headers $headers -ContentType 'application/json'
$GroupID = $Group.Groups.Id
$SearchPhrase = $PWUser
$searchbody = @{“search” = $SearchPhrase}
$Search = Invoke-RestMethod -Method post -Uri "$KeepassURL/api/v4/rest/search"-body (ConvertTo-Json $searchbody) -Headers $headers -ContentType 'application/json'
$SearchID = $Search.Credentials.Id
$KeePassResultscnt = 0
ForEach($Result in $Search.credentials)
{
$CredentialID = $Result.id
If ($Result.GroupId -eq $GroupID)
{
$KeePassResultscnt += 1
}
}
If ($KeePassResultscnt -ge 1)
{
Write-Host "Total number of results found: $cnt"
Write-Host ""
Write-Host ""
Write-Host "ALERT - KeePass already has credentials for this system - can not proceed."
Write-Host "=========================================================================="
Write-Host ""
Write-Host "Search-Phrase: $SearchPhrase"
Write-Host "Search-Folder: $PWFolder"
Write-Host "Amount of results found: $KeePassResultscnt"
Write-Host ""
Write-Host ""
Write-Host ""
Write-Host "Next Steps:"
Write-Host "==========="
Write-Host "- This script will exit now!"
Write-Host "- No changes to the system of KeePass have been applied"
Write-Host "- Go to KeePass and check if this is an old entry and can be renamed/moved"
Write-Host "- Execute the script again"
Write-Host ""
Write-Host ""
pause
EXIT
} Else {
Write-Host ""
Write-Host ""
Write-Host "Writing new credentials to the KeePass server/database"
Write-Host ""
Write-Host ""
$PWEntryDT = Get-Date -Format "O"
$CredEntry = @{
Id = "00000000-0000-0000-0000-000000000000"
Name = "$PWName"
Username = "$PWUser"
Password = "$PWPassword"
Created = "$PWEntryDT"
Modified = "$PWEntryDT"
GroupId = "$GroupID"
Notes = "$PWDescription"
Url = "$ComputerName"
}
Invoke-RestMethod -Method post -Uri "$KeepassURL/api/v4/rest/credential/00000000-0000-0000-0000-000000000000"-body @(ConvertTo-Json $CredEntry) -Headers $headers -ContentType 'application/json'
Write-Host ""
Write-Host ""
Write-Host "Finished writing to KeePass server/database"
Write-Host ""
Write-Host ""
}
pause
Clear-Host
Write-Host ""
Write-Host ""
Write-Host "Please check the following information:"
Write-Host "======================================="
Write-Host ""
Write-Host "Computer Name: $ComputerName"
Write-Host "local Admin: $localAdminUser"
Write-Host "Admin-PW: $PW"
Write-Host ""
Write-Host ""
Write-Host "Make sure the information above are correct!"
Write-Host ""
Write-Host ""
Write-Host "Verify the local Admin and Admin-PW in KeePass!"
Write-Host ""
Write-Host ""
pause
Write-Host ""
Write-Host ""
Write-Host "All information are verified?"
Write-Host ""
Write-Host ""
pause
Clear-Host
Write-Host "Checking and removing (if exists) old local user: $localAdminUser"
Get-LocalUser -Name $localAdminUser | Remove-LocalUser
Clear-Host
Write-Host "Adding new local administrator account: $localAdminUser"
New-LocalUser -Name $localAdminUser -Password $PWencrypted -AccountNeverExpires -PasswordNeverExpires -Description "System specific local administrator account"
$NewUser = Get-LocalUser -Name $localAdminUser
$AdminGroup = Get-LocalGroup -Name "Administrators"
Add-LocalGroupMember -Name $AdminGroup -Member $NewUser
Write-Host ""
Write-Host ""
Write-Host "Finished."
Write-Host ""
Write-Host ""
pause
Write-Host ""
Write-Host ""
Write-Host "Joining this system to the domain and reboot automatically - stay put"
Write-Host ""
Write-Host ""
Write-Host "Note: The system will not reboot if an error occurs. Check the error message in case you see a error."
Write-Host ""
Write-Host ""
Add-Computer -Domain "mydomain.local" -Credential $DomainJoinCredentials -NewName $ComputerName -Restart -Force -OUPath "OU=Computers,OU=San Diego,OU=USA,DC=mydomain,DC=local"
Write-Host ""
Write-Host ""
Write-Host "Computer exists already:"
Write-Host " Check Domain - remove Computer if needed"
Write-Host " Reboot this system"
Write-Host " Rename this system manually after the reboot"
Write-Host ""
Write-Host "Credentials for Domain are wrong:"
Write-Host " Start the script over"
Write-Host ""
Write-Host ""
pause