Skip to content

New-LocalUserAccount

User Management: Creates a new local Windows user account

#Requires -Version 5.1

[CmdletBinding()]
Param(
    [Parameter(Mandatory = $true)]
    [string]$Username,

    [Parameter(Mandatory = $true)]
    [string]$Password,

    [string]$FullName = '',

    [string]$Description = '',

    [string[]]$LocalGroups = @('Users'),

    [switch]$PasswordNeverExpires
)

Process {
    try {
        if (Get-LocalUser -Name $Username -ErrorAction SilentlyContinue) {
            throw "Local user account '$Username' already exists."
        }

        $secPassword = ConvertTo-SecureString $Password -AsPlainText -Force
        
        $userParams = @{
            Name = $Username
            Password = $secPassword
            ErrorAction = 'Stop'
        }
        if ($FullName) { $userParams.Add('FullName', $FullName) }
        if ($Description) { $userParams.Add('Description', $Description) }
        if ($PasswordNeverExpires) { $userParams.Add('PasswordNeverExpires', $true) }

        $user = New-LocalUser @userParams
        
        $addedGroups = @()
        foreach ($groupName in $LocalGroups) {
            try {
                if (Get-LocalGroup -Name $groupName -ErrorAction SilentlyContinue) {
                    Add-LocalGroupMember -Group $groupName -Member $Username -ErrorAction Stop
                    $addedGroups += $groupName
                } else {
                    Write-Warning "Local group '$groupName' was not found. Skipping membership."
                }
            } catch {
                Write-Warning "Failed to add '$Username' to group '$groupName': $_"
            }
        }

        [PSCustomObject]@{
            Username             = $user.Name
            FullName             = $user.FullName
            Enabled              = $user.Enabled
            Description          = $user.Description
            PasswordNeverExpires = $user.PasswordNeverExpires
            LocalGroups          = ($addedGroups -join ', ')
            Created              = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
        }
    }
    catch {
        Write-Error $_
        throw
    }
}

Username for the new local account

Password for the new account

Full name of the user

Account description

Local groups to add the user to (e.g., 'Users', 'Administrators', 'Remote Desktop Users')

Off

Set the password to never expire

An interactive directory of PowerShell scripts.