Windows/DomainControl.ps1
function Remove-Domain { [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory = $true)] [string]$DomainUsername, [Parameter(Mandatory = $true)] [string]$Password, [Parameter()] [string]$WorkgroupName = "WORKGROUP", [Parameter()] [string]$NewComputerName = $env:COMPUTERNAME, [Parameter()] [switch]$Restart ) try { Write-GsLog -Message "Preparing to remove domain and join workgroup '$WorkgroupName'..." -LogType Info $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential ($DomainUsername, $securePassword) if ($PSCmdlet.ShouldProcess("This machine", "Unjoin domain and join $WorkgroupName")) { Remove-Computer -UnjoinDomainCredential $credential -WorkgroupName $WorkgroupName -PassThru -Verbose -Force -Restart:$false Write-GsLog -Message "Successfully remove from domain and joined workgroup '$WorkgroupName'." -LogType Success if ($NewComputerName -ne $env:COMPUTERNAME) { Rename-Computer -NewName $NewComputerName -Force -Restart:$false Write-GsLog -Message "Computer renamed to '$NewComputerName'." -LogType Success } if ($Restart) { Write-GsLog -Message "Restarting computer..." -LogType Info Restart-Computer -Force } } } catch { Write-GsLog -Message "Failed to remove domain: $_" -LogType Error throw } } function Add-Domain { [CmdletBinding(SupportsShouldProcess)] param ( [Parameter(Mandatory = $true)] [string]$DomainName, [Parameter(Mandatory = $true)] [string]$DomainUsername, [Parameter(Mandatory = $true)] [string]$Password, [Parameter()] [switch]$Restart ) try { Write-GsLog -Message "Preparing to join domain '$DomainName'..." -LogType Info $securePassword = ConvertTo-SecureString $Password -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential ($DomainUsername, $securePassword) if ($PSCmdlet.ShouldProcess("This machine", "Join domain $DomainName")) { Add-Computer -DomainName $DomainName -Credential $credential -PassThru -Verbose -Force -Restart:$false Write-GsLog -Message "Successfully joined domain '$DomainName'." -LogType Success if ($Restart) { Write-GsLog -Message "Restarting computer..." -LogType Info Restart-Computer -Force } } } catch { Write-GsLog -Message "Failed to join domain: $_" -LogType Error throw } } Export-ModuleMember -Function '*' Export-ModuleMember -Variable '*' |