# addLocalAccountOnAllServers.ps1
# Feature: using only legacy commands for maximum compatibility

# Set variables
$newUsername='backupAdmin'
$newUserPass='VERYCOMPLEXPASSWORD'
$newUserFullName="Local System Admin"
$newUserDesc="Standardized local admin user"
$newUserGroup="Administrators"

function addLocalAccount{
    param(
        $servers=$env:computername,
        $newUsername='backupAdmin',
        $newUserPass='COMPLEXPASSWORDHERE',
        $newUserFullName="Systems Admin",
        $newUserDesc="Standardized local admin user",
        $newUserGroup="Administrators"
    )
    $results=@()
    $psSessionOptions=New-PSSessionOption -SkipCNCheck -OpenTimeOut 60
    foreach ($server in $servers){
        $pssession=new-pssession $server -SessionOption $psSessionOptions -EA Ignore
        $progress=if($pssession.State -eq 'Opened'){
                Invoke-command -session $pssession -ScriptBlock {
                    param($newUsername,$newUserPass,$newUserFullName,$newUserDesc,$newUserGroup)                            
                    # Check whether username exists and proceed accordingly
                    $usernameExists=$(net user $newUsername)[0] -match $newUsername
                    try{
                        if(!$usernameExists){
                            # Using legacy commands for maximum compatibility
                            $null=NET USER $newUsername $newUserPass /fullname:"$newUserFullName" /comment:"$newUserDesc" /Active:Yes /ADD /Y
                            write-host "$newUserName has been created on $env:computername successfully"
                        }else{
                            # if user exists, ensure that its password is matching the intended value
                            $null=invoke-expression "net user $newUsername $newUserPass" 2>&1
                            write-host "$newUserName exists on $env:computername and its password has been reset"
                        }
                        $isMembershipValid=$(net localgroup $newUserGroup) -match $newUsername
                        if(!$isMembershipValid){
                            $null=invoke-expression "NET LOCALGROUP $newUserGroup $newUsername /ADD /Y" 2>&1
                            write-host "$newUserName has been added to group $newUserGroup on $env:computername successfully"
                        }else{
                            write-host "$newUserName is already a member of group $newUserGroup on $env:computername"
                        }
                        $null=Net user $newUsername /active:yes
                    }catch{
                        write-warning $_
                        return $false
                    }                    
                    # Validation
                    $userEnabled=$(net user $newUsername)[5] -match 'Yes'
                    return $userEnabled
                  
                    # These lines only work in PowerShell 5.1+; hence, they are skipped
                    # New-LocalUser $newUsername -Password $newUserPass -FullName $newUserFullName -Description $newUserDesc
                    # Add-LocalGroupMember -Group $newUserGroup -Member $newUsername
                } -Args $newUsername,$newUserPass,$newUserFullName,$newUserDesc,$newUserGroup
                remove-pssession $pssession
            }else{
                write-warning "$env:computername is unable to connect to $server via WinRM"
                $null
            }
        $result=[pscustomobject]@{
            'computername'=$server
            'localUserExists'=$progress
            }
        write-host $result
        $results+=$result
    }
    return $results
}

# Get all servers, excluding domain controllers
$memberServers=Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true" -and primarygroupid -ne "516"' -Properties Name,Operatingsystem,OperatingSystemVersion,IPv4Address | Sort-Object -Property Operatingsystem | Select-Object -Property Name,Operatingsystem,OperatingSystemVersion,IPv4Address
$servers=$memberServers.Name

$results=addLocalAccount $servers $newUsername $newUserPass $newUserFullName $newUserDesc $newUserGroup

write-host $results