Create Local Admin Accounts

by May 16, 2016

There is no module available for all PowerShell versions that allows to administer local user accounts. Here is a chunk of sample code that illustrates how you nevertheless can automate local account management.

The code creates a new local Administrator account with password. Provided you have sufficient privileges, you can run the script locally as well as remotely:

# where do you want to create the local admin account?
$ComputerName = $env:COMPUTERNAME
# what is the name of the local admin group?
# WARNING: MUST EXIST! MAY BE DIFFERENT IN DIFFERENT LOCALES
$Group = 'Administrators'
# what is the name of the new account?
$Name = 'ServiceAdmin'
# what is the password?
$Password = 'topSecret123'
# what is the description?
$Description = 'Automatically generated local account'

$computer = [ADSI]"WinNT://$($ComputerName),computer"
$user = $computer.Create('User', "$($Name)")
$user.SetPassword($password)
$user.Put('Description',$($Description))    
$user.SetInfo()

# password never expires
$user.UserFlags.value = $user.UserFlags.value -bor 0x10000
$user.CommitChanges()

# add user to group
$group = [ADSI]"WinNT://$($computername)/$($groupname),group" 
$group.add("WinNT://$($Name),user")

Many other management tasks, such as removal of local groups or change of password, can be accomplished in a similar way.

Twitter This Tip! ReTweet this Tip!