New-TempAdminUser.ps1

function New-TempAdminUser
{
  <#
      .SYNOPSIS
      Create a temporary user $UserName member of administrator group and password is set to $password
      .DESCRIPTION
      If user alreadey exist then change its password
      If AD server then make user a member of domain administrators, otherwise user is member of local administrators groups
      Checks that groups names match the OS language (FR/US)
      .EXAMPLE
      CreateTempAdminUser "TempAdmin" "SomeComplexPa$$w0rd"
  #>

  param ([Parameter(Mandatory=$true)][String] $UserName, [Parameter(Mandatory=$true)][String] $password)
  
  Write-Event "Create user $username with password '$password'"
  $users = net user

  #######################
  # cree un compte temporaire en local/domain selon les cas
  #######################

  $users2 = net user

  if ($users2 -match $UserName) { $newuser = net user $username $password }
  else { $newuser = net user $username $password /add }

  $newuser2 = net user

  if ($newuser2 -match $username) { } else { $password = $null }
  $newusergroups = net user $username


  if ($Host.Version.Major -gt 4) {

    $AD = $(try { Get-WindowsFeature -name AD-Domain-Services -ErrorAction Ignore } catch{}) -ne $null
    #$AD = Get-WindowsFeature -name AD-Domain-Services -Erroraction silentlycontinue -informationaction silentlycontinue | select *

    if ($ad.Installed -eq "True") { 

      $groups = net group

      if ($groups) {

        if ($groups -match "administrateurs")
        { $addingtolocalgroup = net localgroup "administrateurs" $username /add | out-null }
        elseif ($groups -match "administrators")
        { $addingtolocalgroup = net localgroup "administrators" $username /add | out-null }
        else { Write-EventError "unable to find the local admin group. debug :" ; Write-EventError $groups }
      }
    }
  }    

  $localgroups = net localgroup

  if ($localgroups) {

    if (($localgroups -match "administrateurs") -and !($newusergroups -match "administrateurs"))
    { $addingtolocalgroup = net localgroup "administrateurs" $username /add | out-null }

    elseif (($localgroups -match "administrators") -and !($newusergroups -match "administrators"))
    { $addingtolocalgroup = net localgroup "administrators" $username /add | out-null }

    elseif (($localgroups -match "administrateurs") -and ($newusergroups -match "administrateurs")) {}
    elseif (($localgroups -match "administrators") -and ($newusergroups -match "administrators")) {}
                    
    else  { Write-EventError "unable to find the local admin group. debug :" ; Write-EventError $localgroups }

    $newuser3 = net user $username
    if ($newuser3 -match "administrat") {  } else { Write-EventError "failed to add temp user to local admin group" ; Exit-Event 1 }
  }
}