Skip to content
Menu
The Lonely Administrator
  • PowerShell Tips & Tricks
  • Books & Training
  • Essential PowerShell Learning Resources
  • Privacy Policy
  • About Me
The Lonely Administrator

Set Local User Account with PowerShell

Posted on April 15, 2014

halfuser The other day I received an email from a student asking for some help in using PowerShell to take care of a user account on a local computer. He not only wanted to be able to set the password, which he had already figured out, but also how to enable or disable the account, which is not obvious or intuitive without experience using ADSI and the WinNT provider. I sent him some suggestions to get him started down the right path. But I realized, I should wrap up this functionality in a PowerShell tool since his task is something I assume many of you need and there are no cmdlets from Microsoft for managing local user accounts.

Manage and Report Active Directory, Exchange and Microsoft 365 with
ManageEngine ADManager Plus - Download Free Trial

Exclusive offer on ADManager Plus for US and UK regions. Claim now!

First, let me point out that it is actually quite easy to manage local user accounts on remote computers using PowerShell. All you need to do is learn how to use the NET USER command and execute it using Invoke-Command.

invoke-command { net user } -computername chi-core01

remote-net-user-1

invoke-command { net user localadmin } -computername chi-core01

remote-net-user-2

The LocalAdmin account on CHI-CORE01 is currently disabled (account active is equal to no). But it is pretty easy to enable and set a new password.

invoke-command { net user localadmin P@ssw0rd /active:Yes } -computername chi-core01

However, this doesn't scale well and the capabilities of the NET USER command might vary by operating system. So here is a PowerShell function that utilizes ADSI to do the same thing.

#requires -version 2.0

Function Set-LocalUserAccount {
<#
.SYNOPSIS
Enable or disable a local user account.

.DESCRIPTION
This command will allow you to set the password of a local user account as well
as enable or disable it. By default, this command will not write anything to
the pipeline unless you use -Passthru.  You must run this under credentials 
that have administrator rights on the remote computer.

.PARAMETER ComputerName 
The name of the computer to connect to. This parameter has an alias of CN.
.PARAMETER UserName 
The name of the local user account on the computer.
.PARAMETER Password 
The new password to set. This parameter has an alias of PWD.
.PARAMETER Status 
Enable or disable the local user account.
.PARAMETER Passthru
Write the user account object to the pipeline
.EXAMPLE
PS C:\> Set-LocalUserAccount SERVER01,SERVER02 DBAdmin -status disable

Disable the local user account DBAdmin on SERVER01 and SERVER02

.EXAMPLE
PS C:\> get-content c:\work\computers.txt | set-localuseraccount LocalAdmin -password "^Crx33t7A"

Sets the password for account LocalAdmin on all computers in computers.txt

.NOTES
Version: 1.0
Author : Jeff Hicks (@JeffHicks)

Learn more:
 PowerShell in Depth: An Administrator's Guide (http://www.manning.com/jones2/)
 PowerShell Deep Dives (http://manning.com/hicks/)
 Learn PowerShell 3 in a Month of Lunches (http://manning.com/jones3/)
 Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/)


  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************

.INPUTS
String
.OUTPUTS
None or System.DirectoryServices.DirectoryEntry

#>

[cmdletbinding(SupportsShouldProcess=$True)]

Param (
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$ComputerName=$env:COMPUTERNAME, 
[Parameter(Position=1,Mandatory=$True,
HelpMessage="What is the name of the local user account?",
ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[string]$UserName, 
[Parameter(ValueFromPipelineByPropertyName=$True)]
[Alias("pwd")]
[string]$Password, 
[ValidateSet("Enable","Disable")]
[string]$Status="Enable",
[switch]$Passthru
)

Begin {
    Write-Verbose "Starting $($myinvocation.mycommand)"
    #define a constant to disable or enable an account
    New-Variable ADS_UF_ACCOUNTDISABLE 0x0002 -Option Constant

    Write-Verbose "Setting local user account $username"
} #begin

Process {
    foreach ($computer in $computername) {
        Write-Verbose "Connecting to $computer"
        Write-Verbose "Getting user account"

        $Account = [ADSI]"WinNT://$computer/$username,user"

        #validate the user account was found
        if (-NOT $Account.path) {
            Write-Warning "Failed to find $username on $computername"
            #bail out
            Return
        }

        #Get current enabled/disabled status
        if ($Account.userflags.value -band $ADS_UF_ACCOUNTDISABLE) {
          $Enabled = $False
        }
        else {
          $Enabled = $True
        }

        Write-verbose "Account enabled is $Enabled"

        if ($enabled -AND ($Status -eq "Disable")) {
            Write-Verbose "disabling the account"
            $value=$Account.userflags.value -bor $ADS_UF_ACCOUNTDISABLE
            $Account.put("userflags",$value)
        }
        elseif ((-NOT $enabled) -AND ($Status -eq "Enable")) {
            Write-Verbose "Enabling the account"
            $value=$Account.userflags.value -bxor $ADS_UF_ACCOUNTDISABLE
            $Account.put("userflags",$value)
        }
        else {
            #account is already in the desired state
            Write-Verbose "No change necessary"
        }

        if ($Password) {
            Write-Verbose "Setting acccount password"
            $Account.SetPassword($Password)
        }
    
        #Whatif
        if ($PSCmdlet.ShouldProcess("$computer\$username")) {
            Write-Verbose "Committing changes"
            $Account.SetInfo()
         }
         if ($Passthru) {
            Write-Verbose "Passing object to the pipeline"
            $Account

         }
    } #foreach
} #process

End {    
    Write-Verbose "Ending $($myinvocation.mycommand)"
} #end
 
} #end Set-LocalUserAccount function

This function should work in PowerShell 2.0 and later. The help content includes some usage examples. You can use this command to simply change the user password, or change the password while enabling or disabling the account. Enabling and disabling is accomplished with a bitwise operation with the userflags value and a constant flag that indicates the account is disabled.

There is probably more that could be added to the command such as setting the comment property and when the account expires. But I'll leave those changes to you for now.


Behind the PowerShell Pipeline

Share this:

  • Click to share on X (Opens in new window) X
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Mastodon (Opens in new window) Mastodon
  • Click to share on LinkedIn (Opens in new window) LinkedIn
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to print (Opens in new window) Print
  • Click to email a link to a friend (Opens in new window) Email

Like this:

Like Loading...

Related

2 thoughts on “Set Local User Account with PowerShell”

  1. Pingback: Rename, Enable and Reset Local Administrator with PowerShell | Windows Bigot
  2. Pingback: Rename, Enable and Reset Local Administrator with PowerShell | PowerShell Scripter

Comments are closed.

reports

Powered by Buttondown.

Join me on Mastodon

The PowerShell Practice Primer
Learn PowerShell in a Month of Lunches Fourth edition


Get More PowerShell Books

Other Online Content

github



PluralSightAuthor

Active Directory ADSI Automation Backup Books CIM CLI conferences console Friday Fun FridayFun Function functions Get-WMIObject GitHub hashtable HTML Hyper-V Iron Scripter ISE Measure-Object module modules MrRoboto new-object objects Out-Gridview Pipeline PowerShell PowerShell ISE Profile prompt Registry Regular Expressions remoting SAPIEN ScriptBlock Scripting Techmentor Training VBScript WMI WPF Write-Host xml

©2025 The Lonely Administrator | Powered by SuperbThemes!
%d