Skip to main content

PowerShell function to check if a user exists, is an Admin, create user, grant folder permissions, and test login credentials.

function CheckLocalUserExists($username)
{
    $objComputer = [ADSI]("WinNT://$env:computername")
    $colUsers = ($objComputer.psbase.children | Where-Object { $_.psBase.schemaClassName -eq "User" } | Select-Object -expand Name)

    $blnFound = $colUsers -contains $username
    if ($blnFound)
    {
        return $true
    }
    else
    {
        return $false
    }
}

function CheckIfUserIsAdmin($username)
{
    $computer = [ADSI]("WinNT://$env:computername,computer")
    $group = $computer.psbase.children.find("Administrators")

    $colMembers = $group.psbase.invoke("Members") | ForEach-Object { $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) }

    $bIsMember = $colMembers -contains $username
    if ($bIsMember)
    {
        return $true
    }
    else
    {
        return $false
    }
}

function AddUser($username, $password)
{
    if (-not (CheckLocalUserExists($username) -eq $true))
    {
        $comp = [adsi] "WinNT://$env:computername,computer"
        $user = $comp.Create("User", $username)
        $user.SetPassword($password)
        $user.SetInfo()
    }
}

function CreateLocalUser($username, $password, $isAdmin)
{
    AddUser $username $password

    if ($isAdmin)
    {
        if (-not (CheckIfUserIsAdmin($username) -eq $true))
        {
            $group = [ADSI]"WinNT://$env:computername/Administrators,group"
            $group.add("WinNT://$env:computername/$username")
        }
    }

    return $true
}

function CheckUserViaLogon($username, $password)
{
    $signature = @'
    [DllImport("advapi32.dll")]
    public static extern int LogonUser(
        string lpszUserName,
        string lpszDomain,
        string lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);
'@

    $type = Add-Type -MemberDefinition $signature -Name Win32Utils -Namespace LogOnUser -PassThru

    [IntPtr]$token = [IntPtr]::Zero

    $value = $type::LogOnUser($username, $env:computername, $password, 2, 0, [ref] $token)

    if ($value -eq 0)
    {
        return $false
    }

    return $true
}

function CheckUsernamePasswordCombination($user, $password)
{
    if (($user) -AND ($password))
    {
        if (CheckLocalUserExists($user) -eq $true)
        {
            if (CheckUserViaLogon $user $password)
            {
                return $true
            }
            else
            {
                Write-Error "Failed to validate user '$user' with specified password"
                return $false
            }
        }
    }

    return $true
}

# Gives a user permissions to a file on disk
# Usage: GrantPermissionsOnDisk $deploymentUserName 'FullControl' 'ContainerInherit,ObjectInherit' 'C:\inetpub\wwwroot'
function GrantPermissionsOnDisk($username, $type, $options, $path)
{
    trap [Exception]
    {
        Write-Error "Not granted permissions: type: '$type', user: '$username', path: '$path'"
    }

    $acl = (Get-Item $path).GetAccessControl("Access")
    $accessrule = New-Object system.security.AccessControl.FileSystemAccessRule($username, $type, $options, "None", "Allow")
    $acl.AddAccessRule($accessrule)
    Set-Acl -AclObject $acl $path
    # write-log $INFO $Resources.GrantedPermissions $type $username $path
}

function GetAdminGroupName()
{
    $securityIdentifier = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-32-544")
    $adminName = $securityIdentifier.Translate([System.Type]::GetType("System.Security.Principal.NTAccount")).ToString()

    $array = $adminName -split "\\"
    if ($array.Count -eq 2)
    {
        return $array[1]
    }

    return "Administrators"
}