Skip to content

New-LocalUserRemote

Windows: Creates a new local user account on a computer

#Requires -Version 5.1

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

    [string]$FullName,

    [string]$Description,

    [securestring]$Password,

    [switch]$PasswordNeverExpires,

    [switch]$Disabled,

    [string]$ComputerName = $env:COMPUTERNAME,

    [pscredential]$Credential
)

Process {
    try {
        $scriptBlock = {
            Param($UserName, $UserFull, $UserDesc, $UserPass, $PassNever, $IsDisabled)
            $params = @{
                'Name' = $UserName
                'Confirm' = $false
                'ErrorAction' = 'Stop'
            }
            if ($UserFull) { $params.Add('FullName', $UserFull) }
            if ($UserDesc) { $params.Add('Description', $UserDesc) }
            if ($UserPass) { 
                $params.Add('Password', $UserPass)
                if ($PassNever) { $params.Add('PasswordNeverExpires', $true) }
            }
            else {
                $params.Add('NoPassword', $true)
            }
            if ($IsDisabled) { $params.Add('Disabled', $true) }
            
            New-LocalUser @params
            Get-LocalUser -Name $UserName | Select-Object Name, SID, Enabled, Description
        }

        if ($ComputerName -ne $env:COMPUTERNAME) {
            $invokeParams = @{
                'ComputerName' = $ComputerName
                'ScriptBlock'  = $scriptBlock
                'ArgumentList' = @($Name, $FullName, $Description, $Password, $PasswordNeverExpires, $Disabled)
                'ErrorAction'  = 'Stop'
            }
            if ($null -ne $Credential) {
                $invokeParams.Add('Credential', $Credential)
            }

            $result = Invoke-Command @invokeParams
        }
        else {
            $result = &$scriptBlock -UserName $Name -UserFull $FullName -UserDesc $Description -UserPass $Password -PassNever $PasswordNeverExpires -IsDisabled $Disabled
        }

        $output = [PSCustomObject]@{
            Name         = $result.Name
            SID          = $result.SID.Value
            Enabled      = $result.Enabled
            Description  = $result.Description
            ComputerName = $ComputerName
            Action       = "UserCreated"
            Timestamp    = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }

        Write-Output $output
    }
    catch {
        throw
    }
}

Specifies the user name for the new account.

Specifies the full name for the user account.

Specifies a description for the user account.

Specifies a secure string used as the initial password.

Off

If set, the password for the account will never expire.

Off

If set, creates the account in a disabled state.

Specifies the name of the target computer. Defaults to the local computer.

Specifies a PSCredential object for remote connection.

An interactive directory of PowerShell scripts.