Добавление пользователя в windows 10 powershell

Относительно недавно Microsoft добавила в Windows стандартный PowerShell модуль для управления локальными пользователями и группами под названием Microsoft

Относительно недавно Microsoft добавила в Windows стандартный PowerShell модуль для управления локальными пользователями и группами под названием Microsoft.PowerShell.LocalAccounts. Ранее этот командлет нужно было качать и импортировать в PowerShell отдельно. В Windows Server 2016 и Windows 10 модуль LocalAccounts теперь доступен по умолчанию, т.к. он входит в состав PowerShell 5.1. В более ранние версии Windows для использования модуля управления локальными аккаунтами нужно установить Windows Management Framework 5.1.

Содержание:

  • Модуль LocalAccounts
  • Управление локальными пользователями Windows с помощью PowerShell
  • Управление локальными группам Windows с помощью PowerShell

Модуль LocalAccounts

Всего в модуль входит 15 командлетов. Полный список командлетов в модуле LocalAccounts можно вывести так:

Get-Command -Module Microsoft.PowerShell.LocalAccounts

Модуль Microsoft.PowerShell.LocalAccounts

  • Add-LocalGroupMember – добавить пользователя в локальную группу
  • Disable-LocalUser – отключить локальную учетную запись
  • Enable-LocalUser – включить учетную запись (разблокировать)
  • Get-LocalGroup – получить информацию о локальной группе
  • Get-LocalGroupMember – получить список пользователей в локальной группе
  • Get-LocalUser – получить информацию о локальном пользователе
  • New-LocalGroup – создать новую локальную группы
  • New-LocalUser – создать пользователя
  • Remove-LocalGroup – удалить группу
  • Remove-LocalGroupMember – удалить члена из группы
  • Remove-LocalUser – удалить локального пользователя
  • Rename-LocalGroup – переименовать группу
  • Rename-LocalUser – переименовать пользователя
  • Set-LocalGroup – изменить группу
  • Set-LocalUser – изменить пользователя

Далее рассмотрим несколько типовых задач по управлению локальными пользователями и группами на компьютере с Windows 10 при помощи PowerShell командлетов из состава модуля LocalAccounts.

Управление локальными пользователями Windows с помощью PowerShell

Выведем список имеющихся на компьютере локальных пользователей Windows:

Get-LocalUser

Как вы видите, на компьютере имеется 7 локальных учетных записей, 3 из которых отключены (Enabled=False).

Чтобы вывести все свойства конкретной локальной учетной записи (аналог комадлета для получения иформации о пользователях из AD — Get-ADUser), выполните:

Get-LocalUser -Name ‘root’ | Select-Object *


AccountExpires :
Description :
Enabled : True
FullName :
PasswordChangeableDate : 4/23/2018 11:23:48 PM
PasswordExpires :
UserMayChangePassword : True
PasswordRequired : False
PasswordLastSet : 4/22/2018 11:23:48 PM
LastLogon : 7/15/2018 9:04:32 PM
Name : root
SID : S-1-5-21-3650440056-3766451173-3310994491-1001
PrincipalSource : Local
ObjectClass : User

Чтобы получить конкретный атрибут пользователя, например, время последней смены пароля, выполните:

Get-LocalUser -Name ‘root’ | Select-Object PasswordLastSet

Get-LocalUser получаем информацию о локальном пользователе

Создадим нового локального пользователя с помощью командлета New-LocalUser. Данный командлет позволяет создать следующие типы учетных записей:

  • Локальные учетных записи Windows
  • Учетные записи Microsoft
  • Учетные записи Azure AD

При создании учётной записи пользователя с помощью New-LocalUser нельзя указывать ее пароль в качестве аргумента Password в открытом виде. Предварительно пароль нужно сконвертировать в безопасную строку, запросив пароль интерактивно:

$UserPassword = Read-Host –AsSecureString

Или указав пароль непосредственно в консоли PoSh:

$UserPassword = ConvertTo-SecureString "Pa$$word!!" -AsPlainText -Force

New-LocalUser "SIvanov" -Password $UserPassword -FullName "Sergey Ivanov" -Description "Local Account dlya udalennogo vhoda"

Для создания пользователя в домене AD нужно использовать командлет New-ADUser.

Чтобы изменить пароль пользователя, воспользуйтесь командой Set-LocalUser (предполагаем, что вы уже преобразовали новый пароль в SecureString):

Set-LocalUser -Name sivanov -Password $UserPassword –Verbose

New-LocalUser создать локального пользователя

Чтобы установить флаг «Срок действия пароля пользователя не истекает» («Password never expired»), выполните:

Set-LocalUser -Name sivanov –PasswordNeverExpires $True

Как видите, вам не нужно преобразовывать значение UserAccountControl, как при управлении свойствами учётной записи в AD.

Как вы помните, вы можете авторизоваться в Windows 10 под учетными записями Microsoft. Если нужно создать нового пользователя, связанного с аккаунтом Microsoft, выполните следующую команду (обратите внимание, что пароль аккаунта указывать не нужно, т.к. он хранится в Microsoft).

New-LocalUser -Name "MicrosoftAccount[email protected]" -Description "Это учетка в Microsoft"

Для создания локальной учётной записи, которая связана с вашим аккаунтом в Azure AD (например, вы пользуетесь Office 365), выполните команду:

New-LocalUser -Name "AzureAD[email protected]" -Description "Это учетка в Azure AD"

Чтобы удалить этого локального пользователя, выполните:

Remove-LocalUser -Name sivanov -Verbose

Управление локальными группам Windows с помощью PowerShell

Теперь выведем список локальных групп на компьютере:

Get-LocalGroup

Get-LocalGroup

Создадим новую группу:

New-LocalGroup -Name 'RemoteSupport' -Description 'Remote Support Group'

Теперь добавим в новую группу несколько локальных учетных записей и группу локальных администраторов:

Add-LocalGroupMember -Group 'RemoteSupport' -Member ('SIvanov','root', 'Администраторы') –Verbose

Если ваш компьютер входит в домен, то вы можете добавить в локальную группы и доменные аккаунты или группы. Для этого их нужно указывать в формате DomainNameuser2 или DomainName’domain admins’.

Add-LocalGroupMember добавить пользователя в доменную группу

Также вы можете добавить пользователя в группы с помощью следующего конвейера (добавим пользователя в локальные администраторы):

Get-Localuser -Name 'sivanov' | Add-LocalGroupMember -Group 'Administrators'

Выведем список пользователей в локальной группе:

Get-LocalGroupMember -Group 'RemoteSupport'

Как вы видите, мы используем только локальные учетные записи (PrincipalSource – Local). Однако здесь могут быть доменные аккаунты (domain), учетные записи Microsoft (MicrosoftAccount) и аккаунты из Azure (AzureAD).

Get-LocalGroupMember -Group 'RemoteSupport'

Чтобы вывести список групп, в которых состоит конкретный пользователь, придется перебрать все локальные группы на компьютере:

foreach ($LocalGroup in Get-LocalGroup)
{
if (Get-LocalGroupMember $LocalGroup -Member 'sivanov' –ErrorAction SilentlyContinue)
{
$LocalGroup.Name
}
}

Чтобы убрать пользователя из группы, выполните:

Remove-LocalGroupMember -Group 'RemoteSupport' –Member 'sivanov'

Для управления локальными пользователями на удаленном компьютере нужно сначала подключится к нему через WinRM командлетами Invoke-Command или Enter-PSSession.

Например, нам нужно собрать список учетных записей в локальной группе на удаленных компьютерах:

$s = new-pssession -computer pc01,pc02,pc03

invoke-command -scriptblock {Get-LocalGroupMember -Group 'RemoteSupport'} -session $s -hidecomputername | select * -exclude RunspaceID | out-gridview -title "LocalAdmins"

When you need to create a local user in Windows 10 or 11 you can use the User Accounts control panel. But we can also use PowerShell to create a new local user. This way we can easily automate creating a local account on Windows devices.

To create a local user with PowerShell you will need to have administrator access to the computer and run PowerShell as admin (elevated). Otherwise, you won’t be able to create accounts.

In this article, I will explain how you can create a new localuser. At the end of the article, I have two PowerShell scripts that you can use to create a local user.

In this article

To create a new local user we are going to use the New-LocalUser cmdlet in PowerShell. We have the option to set a password for the account or create an account without a password.

There are also a couple of other useful parameters that we can use:

Parameter Description
-Name Login name of the account – max 20 characters
-Password Password – supplied with a secure string
-Description Description of the account
-AccountExpires DateTime object when the account expires
-AccountNeverExpires Account does not expire
-Disabled Creates the account as disabled
-FullName The display name of the account
-PasswordNeverExpires Password does not expire
-UserMayNotChangePassword User can’t change the password
New-LocalUser cmdlet parameters

So to quickly create a local user account with PowerShell we can do the following:

$password = Read-Host -AsSecureString
New-LocalUser -Name "LazyUser" -Password $password -FullName "Lazy User" -Description "Test user"

new localuser

PowerShell New localuser

This small PowerShell script will require you to first enter the password, after which the user is created with the given password.

Providing the Password

As you can see this won’t allow you to run the script autonomous, because you will need to enter a password. This is also the challenge with creating local users, most of the time you want to supply the password in a secure way.

If you run the script remotely or under your own supervision then you could write the password inside a PowerShell script and convert it to a secure string. But keep in mind, anyone who opens the script is able to read the password!

# Username and Password
$username = "LazyUser"
$password = ConvertTo-SecureString "LazyAdminPwd123!" -AsPlainText -Force  # Super strong plane text password here (yes this isn't secure at all)

# Creating the user
New-LocalUser -Name "$username" -Password $password -FullName "$username" -Description "Lazy Test user"

You could save this into a ps1 file and simply run it in an elevated PowerShell session.

Setting the Expired Date

By default, the new user account won’t expire, but with the New-LocalUser cmdlet, we can set an expiration date for the account. For the date we will need to use a PowerShell DateTime object:

$date = Get-Date -Year 2022 -Month 06 -Day 10

# Creating the user
New-LocalUser -Name "$username" -Password $password -AccountExpires $date -FullName "$username" -Description "Lazy Test user"

Making user member of a group with Add-LocalGroupMember

After you have created the user you will need to make it a member of a local group. Without it, the user won’t be able to log on. To make the user member of a group we are going to use the Add-LocalGroupMember cmdlet.

The Add-LocalGroupMember only requires the group name and the member that you want to add:

Add-LocalGroupMember -Group Users -Member LazyUser

The cmdlet doesn’t give any output on success, only an error when the group name or member isn’t found.

You can also add multiple users to a local group with PowerShell. Simply comma separate the members in the cmdlet:

Add-LocalGroupMember -Group Users -Member "LazyUser", "LazyUser2"

Complete Script for new localuser in PowerShell

I have created two scripts that will help you with creating a local user account with PowerShell. In both scripts, I have added the option to write a log file. This log file is stored on a network share, allowing you to easily check if the creation is successful on the computer.

The first script has a password set in the script, so you can simply run the script on a computer. Keep in mind that you will need to have administrator access to create a local user account!

<#
.SYNOPSIS
  Create local admin acc

.DESCRIPTION
  Creates a local administrator account on de computer. Requires RunAs permissions to run

.OUTPUTS
  none

.NOTES
  Version:        1.0
  Author:         R. Mens - LazyAdmin.nl
  Creation Date:  25 march 2022
  Purpose/Change: Initial script development
#>

# Configuration
$username = "adminTest"   # Administrator is built-in name
$password = ConvertTo-SecureString "LazyAdminPwd123!" -AsPlainText -Force  # Super strong plane text password here (yes this isn't secure at all)
$logFile = "\serverfolderlog.txt"

Function Write-Log {
  param(
      [Parameter(Mandatory = $true)][string] $message,
      [Parameter(Mandatory = $false)]
      [ValidateSet("INFO","WARN","ERROR")]
      [string] $level = "INFO"
  )
  # Create timestamp
  $timestamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")

  # Append content to log file
  Add-Content -Path $logFile -Value "$timestamp [$level] - $message"
}

Function Create-LocalAdmin {
    process {
      try {
        New-LocalUser "$username" -Password $password -FullName "$username" -Description "local admin" -ErrorAction stop
        Write-Log -message "$username local user crated"

        # Add new user to administrator group
        Add-LocalGroupMember -Group "Administrators" -Member "$username" -ErrorAction stop
        Write-Log -message "$username added to the local administrator group"
      }catch{
        Write-log -message "Creating local account failed" -level "ERROR"
      }
    }    
}

Write-Log -message "#########"
Write-Log -message "$env:COMPUTERNAME - Create local admin account"

Create-LocalAdmin

Write-Log -message "#########"

The script will make the user member of the Administrators group in this case. You can of course change this to any other group. Make sure that you set the username, password, and logfile path in this first part of the script.

You can also download the complete script here from my Github repository.

Local User account script

The second script creates a local user account that is a member of the user’s groups. The difference with the first script is that this script will ask for the password.

<#
.SYNOPSIS
  Create local user acc

.DESCRIPTION
  Creates a local user account on de computer. Requires RunAs permissions to run

.OUTPUTS
  none

.NOTES
  Version:        1.0
  Author:         R. Mens - LazyAdmin.nl
  Creation Date:  25 march 2022
  Purpose/Change: Initial script development
#>

# Configuration
$username = "LazyTestUser"   # UserName
$fullName = "Lazy Test User" # Full name
$logFile = "\serverfolderlog.txt"

Function Write-Log {
  param(
      [Parameter(Mandatory = $true)][string] $message,
      [Parameter(Mandatory = $false)]
      [ValidateSet("INFO","WARN","ERROR")]
      [string] $level = "INFO"
  )
  # Create timestamp
  $timestamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")

  # Append content to log file
  Add-Content -Path $logFile -Value "$timestamp [$level] - $message"
}

Function Create-LocalUser {
    process {
      try {
        New-LocalUser "$username" -Password $password -FullName "$fullname" -Description "local user" -ErrorAction stop
        Write-Log -message "$username local user created"

        # Add new user to administrator group
        Add-LocalGroupMember -Group "Users" -Member "$username" -ErrorAction stop
        Write-Log -message "$username added to the local users group"
      }catch{
        Write-log -message "Creating local account failed" -level "ERROR"
      }
    }    
}

# Enter the password
Write-Host "Enter the password for the local user account" -ForegroundColor Cyan
$password = Read-Host -AsSecureString

Write-Log -message "#########"
Write-Log -message "$env:COMPUTERNAME - Create local user account"

Create-LocalUser

Write-Log -message "#########"

Again, you can download the complete script here from my Github repository.

Wrapping Up

The New-LocalUser should also be capable of creating a local account that is connected to a Microsoft account. But the username is still limited to 20 characters and doesn’t accept the @ symbol. So for now we are limited to local accounts only.

I hope this article helped you with creating a local user account with PowerShell. If you have any questions, just drop a comment below.

Для получения списка локальных пользователей в Powershell, созданию новых, а так же для работ с группами есть множество команд. Что бы увидеть все их выполните команду:

Get-Command -Module Microsoft.PowerShell.LocalAccounts

Powershell работа с локальными пользователями

Если нам нужно увидеть параметры, которые команды еще принимают, можно выполнить эту команду (на примере Get-LocalUser):

Get-Command Get-LocalUser -Syntax

Получение списка локальных пользователей Powershell

Получение списка локальных пользователей в Powershell Get-ADUser

Так мы получим список учетных записей:

Get-LocalUser

Мы можем получить такую информацию не обо всех учетных записях, а из конкретных групп. Так я получу локальных администраторов т.к. они находятся в соответствующей группе:

Get-LocalGroupMember -Group Administrators

Получение списка локальных пользователей и администраторов Powershell

Если требуется получить какие-то дополнительные параметры (свойства) объекта. Для того что бы узнать все параметры:

Get-LocalUser | Get-Member

А что бы вывести их все сразу:

Get-LocalUser | select *

get-localuser параметры

Так, например, я получу все объекты, которые активны:

Get-LocalUser | where -Property Enabled -eq $true

А так даты последнего входа только у тех объектов, которые включены:

Get-LocalUser | where -Property Enabled -eq $true | Select -Property LastLogon

Создание локального пользователя Powershell и добавление в группу

Так мы создадим нового пользователя с именем «IT_Support» с паролем «Parol12!»:

$password = ConvertTo-SecureString -String "Parol12!" -AsPlainText -Force
New-LocalUser -Name "IT_Support" -Password $password -PasswordNeverExpires

Если мы не укажем ключ PasswordNeverExpires — пароль будет действовать месяц.

Powershell смена пароля

Затем добавим нового пользователя в группу администраторов:

Add-LocalGroupMember -Group Administrators -Member "IT_Support"

Ключ Member способен принимать несколько значений, т.е. мы можем добавить множество аккаунтов. Для этого нужно написать их через запятую.

При создании нового объекта есть еще несколько ключей:

  • AccountExpires — время активности учетной записи. Если не указан этот ключ, то такого срока нет. Если мы хотим указать этот срок нам нужна переменная datetime. Примеры с датой и временем в Powershell мы уже разбирали.
  • AccountNeverExpires — если не указан ключ выше, то у нас работает этот ключ.
  • Description — описание учетной записи по желанию.
  • Disabled — по умолчанию аккаунт включен, мы можем указать обратное.
  • FullName — имя и фамилия например.
  • NoPassword — учетная запись создается без пароля.
  • UserMayNotChangePassword — запрещает смену пароля.

Удаление локальных пользователей

Для примера так мы можем удалить объект, который создавали раннее из группы:

Remove-LocalGroupMember -Group Administrators -Member IT_Support

Если мы хотим отключить объект:

Disable-LocalUser -Name IT_Support

И удалить:

Remove-LocalUser -Name IT_Support

Смена пароля локального администратора в Powershell

Изменение существующих объектов делается с помощью команд с глаголом Set. На примере администратора сменим пароль:

$password = ConvertTo-SecureString -String "Parol12!" -AsPlainText -Force
Set-LocalUser -Name "Администратор" -Password $password

Мы можем изменить все те же параметры, что и в случае создания учетной записи (перечислены выше). Например так мы можем отключить срок действия пароля:

Set-LocalUser -Name "IT_Support" -PasswordNeverExpires

Отсутствуют только те ключи, которые выведены в отдельный командлет. Например так мы можем включить объект:

Enable-LocalUser -Name "IT_Support2"

Теги:

#powershell

On Windows 10, you can create a local user account or Microsoft account that allows you to take advantage of additional benefits, such as settings syncing across devices and seamless integration to various Microsoft cloud services.

If you use Windows 10, you’re likely already utilizing an account connected to a Microsoft account. However, if you have to set up another account (in addition to using the Settings app and Command Prompt), you can create a new local user account from PowerShell.

This guide will teach you the steps to create and delete a new local user account using PowerShell on Windows 10.

  • Create new local user account from PowerShell
  • Delete new local user account from PowerShell

Create new local user account from PowerShell

To create a standard or administrator local account with PowerShell, use these steps:

  1. Open Start on Windows 10.

  2. Search for PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to temporarily store the password in a secure string inside the “$Password” variable and press Enter:

    $Password = Read-Host -AsSecureString
  4. Type the password for the new Windows 10 account and press Enter.

  5. Type the following command to create the new account with PowerShell and press Enter:

    New-LocalUser "NEW_ACCOUNT_NAME" -Password $Password -FullName "USER_FULL_NAME" -Description "DESCRIPTION"

    PowerShell create local account

    In the command, change NEW_ACCOUNT_NAME for the account name and USER_FULL_NAME for the user’s full name. Also, replace DESCRIPTION with the description you want to use for the account.

  6. Type the following command to add the Windows 10 account to the correct user group and press Enter:

    Add-LocalGroupMember -Group "Administrators" -Member "NEW_ACCOUNT_NAME"

    PowerShell change account type

    In the command, make sure to change NEW_ACCOUNT_NAME for the account name. In the above command, we add the new account to the Administrators group, which gives the user full access to the computer. However, if you want the user to have limited access, you can add the account to the Users group, making it a “Standard User.”

Once you complete the steps, the new account will be set up on the device with full access using administrative privileges. Of course, this is unless you added the account to the “Users” group, in which case the account will be a limited standard account.

Connect account to Microsoft

Using PowerShell should also be possible to create a user account connected to a Microsoft account with this command: New-LocalUser -Name "MicrosoftAccount[email protected]" -Description "Microsoft account description". However, a bug still returns “New-LocalUser: Cannot validate argument on parameter ‘Name.’ The character length of the 36 arguments is too long. Shorten the character length of the argument so it is fewer than or equal to “20” characters, and then try the command again” message. As a result, the easiest way to get around this problem is to create a local account and then use the Settings app to link it with a Microsoft account.

To link a local account with a Microsoft account, use these steps:

  1. Open Settings.

  2. Click on Accounts.

  3. Click on Your Info.

  4. Click the “Sign in with your Microsoft account instead” option.

  5. Continue with the on-screen directions to connect your account to a Microsoft account.

After you complete the steps, the new account will be connected to the Microsoft account you specified.

Delete new local user account from PowerShell

To delete an account with PowerShell on Windows 10, use these steps:

  1. Open Start.

  2. Search for Windows PowerShell, right-click the top result, and select the Run as administrator option.

  3. Type the following command to delete the user account and press Enter:

    Remove-LocalUser -Name "USER_ACCOUNT_NAME"

    PowerShell delete account

    In the command, change USER_ACCOUNT_NAME with the account name you want to remove.

After you complete the steps, the account will be deleted from the computer. However, the user account data will remain. If you want to delete both account and data, the easiest way to delete it is using the “Accounts” page from the Settings app.

We may earn commission for purchases using our links to help keep offering the free content. Privacy policy info.

All content on this site is provided with no warranties, express or implied. Use any information at your own risk. Always backup of your device and files before making any changes. Privacy policy info.

To help admins manage local users and groups with PowerShell more easily, Microsoft provides a cmdlet collection called Microsoft.PowerShell.LocalAccounts. Previously, you had to download and import it into PowerShell explicitly, and also install Windows Management Framework 5.1; in the Windows Server 2016 and Windows 10 operating systems, the cmdlet collection is included as a standard module.

There are 15 cmdlets in the LocalAccounts module. You can view the full list by running the following command:

Get-Command -Module Microsoft.PowerShell.LocalAccounts

Account Managing with PowerShell 1

  • Add-LocalGroupMember — Add a user to the local group
  • Disable-LocalUser —Disable a local user account
  • Enable-LocalUser — Enable a local user account
  • Get-LocalGroup — View local group preferences
  • Get-LocalGroupMember — View the list of all local group members
  • Get-LocalUser — View a local user account’s preferences
  • New-LocalGroup — Create a new local group
  • New-LocalUser — Create a new local user account
  • Remove-LocalGroup — Remove a local group
  • Remove-LocalGroupMember — Remove a member from a local group
  • Remove-LocalUser — Remove a local user account
  • Rename-LocalGroup — Rename a local group
  • Rename-LocalUser — Rename a local user account
  • Set-LocalGroup — Change the settings of a local group
  • Set-LocalUser — Change the account settings of a local user

Managing Local User Accounts with PowerShell

Let’s see how you can use these commands to perform common tasks related to managing local users on a Windows 10 computer.

Listing users and their properties with PowerShell

First, let’s get a list of all local user accounts on the machine. We’ll use the Get-LocalUser cmdlet:

Get-LocalUser

Account Managing with PowerShell 2

As you can see, we have two local user accounts, and one of them is disabled (the one that has “False” in the “Enabled” column).

If you want to output all the properties and their values for a local user account, you need to use the Get-LocalUser cmdlet with the following parameters:

Get-LocalUser -Name ‘guest’ | Select-Object *

Account Managing with PowerShell 3

To get the value of a particular local user account attribute, type its name after the Select-Object parameter. In this example, we want to know the value of the PasswordLastSet attribute for the account with the username “administrator”:

Get-LocalUser -Name ‘administrator’ | Select-Object PasswordLastSet

Account Managing with PowerShell 4

Creating a local user with PowerShell

Let’s create a new user with the help of the New-LocalUser cmdlet. This cmdlet can create the following types of user accounts:

  • Windows local user accounts
  • Microsoft accounts
  • Azure Active Directory accounts

When creating a local user account, never type in the password as plain text; always convert it to a secure string using the ?AsSecureString or ?ConvertTo-SecureString parameter. Here’s the command for creating a new local user account:

$UserPassword = Read-Host –AsSecureString
New-LocalUser "Netwrix" -Password $UserPassword -FullName "Netwrix" -Description "CompleteVisibility"

In a Windows 10 environment, users can authorize under their Microsoft accounts, so we can create a new local user account that binds to a Microsoft account’s credentials. Use the following script to do this (note that you don’t need to type in the password because it is stored in the Microsoft cloud):

New-LocalUser -Name "MicrosoftAccountSomeAccount@outlook.com" -Description "Microsoft Account"

In order to create a local account that binds to your Azure AD, use the following command:

New-LocalUser -Name "AzureADNetwrix@enterprise.com" -Description "Azure AD Account"

Changing a local user’s password or password properties with PowerShell

To change the password of a local user account, we need to use the Set-LocalUser cmdlet. Let’s change the local admin password:

$UserPassword = Read-Host –AsSecureString
Set-LocalUser -Name Administrator -Password $UserPassword –Verbose

To set the Password never expires to a local user with PowerShell, we need to run the following script:

Set-LocalUser -Name Netwrix –PasswordNeverExpires $False

Deleting a local user account with PowerShell

To remove a local user account, you need to use the Remove-LocalUser cmdlet:

Remove-LocalUser -Name Netwrix -Verbose

Managing Local Groups with PowerShell

Now let’s turn our attention from local users to local groups.

Reviewing local groups with PowerShell

First, let’s get a list of all groups on our Windows Server:

Get-LocalGroup

Account Managing with PowerShell 5

Adding a local group with PowerShell

Now let’s create a new group:

New-LocalGroup -Name 'Netwrix Users' -Description 'Netwrix Users Group'

Adding users to a local group with PowerShell

To add a user (or a group) to a local group, we need to use the Add-LocalGroupMember cmdlet. For example, suppose we want to add users to the local Administrators group, but we don’t want to add them one by one. Let’s add a group to local Administrators, namely the “Netwrix Users” group:

Add-LocalGroupMember -Group 'Administrators' -Member ('Netwrix',’Netwrix Users') –Verbose

If your computer or server is a part of the domain, you can also add domain account and groups to local groups in order to give those users special local rights on the server. Add them using the format “DomainNameUser” (for a user) or “DomainNameDomain Group” (for a group).

Viewing the membership of a particular group with PowerShell

Now let’s list all the members of a particular local group:

Get-LocalGroupMember -Group 'Netwrix Users'

Account Managing with PowerShell 6

As you can see, the command shows all the local account and groups that are members of the group “Netwrix Users”. Although only local accounts and groups are listed here, this command will also show any domain users and group, as well as all Microsoft and Azure AD accounts.

Viewing all groups that a user is a member of using PowerShell

To list all the groups that a particular user is a member of, we’d run the following script:

foreach ($LocalGroup in Get-LocalGroup)
{
if (Get-LocalGroupMember $LocalGroup -Member 'Guest' –ErrorAction SilentlyContinue)
{
$LocalGroup.Name
}
}

Account Managing with PowerShell 7

Removing a local group with PowerShell

To remove a local user account from a group, you need to use the Remove-LocalGroupMember cmdlet:

Remove-LocalGroupMember -Group 'Netwrix Users' –Member 'guest'

Managing local users and groups remotely with PowerShell

If you want to manage local user account and groups remotely, you need to connect to the remote workstations via WinRM using the Invoke-Command and Enter-PSSession cmdlets. For example if we want to output the membership of the local Admin group remotely on multiple computers we need to run the following script:

$search = new-pssession -computer pcname1,pcname2,pcname3
invoke-command -scriptblock {Get-LocalGroupMember -Group 'Administrators'} -session $search -hidecomputername | select * -exclude RunspaceID | out-gridview -title "LocalAdmins"

As you can see, it is rather easy to manage local groups and users via PowerShell, but to ensure security, compliance and business continuity, it’s essential to audit all these changes. To learn about configuring native auditing, please refer to the Windows Server Auditing Quick Reference Guide.

Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips and tricks that can dramatically improve your system administration experience.

I need to create a new local user account, and then add them to the local Administrators group. Can this be done in PowerShell?

EDIT:

# Create new local Admin user for script purposes
$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"

$LocalAdmin = $Computer.Create("User", "LocalAdmin")
$LocalAdmin.SetPassword("Password01")
$LocalAdmin.SetInfo()
$LocalAdmin.FullName = "Local Admin by Powershell"
$LocalAdmin.SetInfo()
$LocalAdmin.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
$LocalAdmin.SetInfo()

I have this, but was wondering if there is anything more PowerShell-esque.

asked Mar 1, 2013 at 21:20

PnP's user avatar

4

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK — you can’t set all the options but it’s a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

Cristian Ciupitu's user avatar

answered May 20, 2013 at 13:02

SinisterPenguin's user avatar

3

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccountusr name@Outlook.com" -Description "Description of this account." 

answered Sep 12, 2016 at 15:44

codevision's user avatar

codevisioncodevision

4,88736 silver badges48 bronze badges

4

Try using Carbon’s Install-User and Add-GroupMember functions:

Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'

Disclaimer: I am the creator/maintainer of the Carbon project.

answered Jul 10, 2013 at 3:58

Aaron Jensen's user avatar

Aaron JensenAaron Jensen

25.2k15 gold badges79 silver badges88 bronze badges

3

As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):

As much as we might hate to admit it, there are still no Windows
PowerShell cmdlets from Microsoft that permit creating local user
accounts or local user groups. We finally have a Desired State
Configuration (DSC ) provider that can do this—but to date, no
cmdlets.

Slogmeister Extraordinaire's user avatar

answered Jun 12, 2015 at 20:49

rasx's user avatar

rasxrasx

5,2162 gold badges45 silver badges58 bronze badges

Import-Csv C:test.csv |
Foreach-Object {
  NET USER    $ _.username   $ _.password /ADD
  NET LOCALGROUP "group" $_.username  /ADD
}

edit csv as username,password
and change «group» for your groupname

:) worked on 2012 R2

Piotr Adam Milewski's user avatar

answered Jan 7, 2018 at 0:06

Anderson Abu Soares's user avatar

$sec_pass = ConvertTo-SecureString -String "SomePasword" -AsPlainText -Force
New-LocalUser -Name username -FullName username -PasswordNeverExpires -Password $sec_pass
Add-LocalGroupMember -Group Administrators -Member username

answered May 12, 2022 at 10:35

Papa Smurf's user avatar

I need to create a new local user account, and then add them to the local Administrators group. Can this be done in PowerShell?

EDIT:

# Create new local Admin user for script purposes
$Computer = [ADSI]"WinNT://$Env:COMPUTERNAME,Computer"

$LocalAdmin = $Computer.Create("User", "LocalAdmin")
$LocalAdmin.SetPassword("Password01")
$LocalAdmin.SetInfo()
$LocalAdmin.FullName = "Local Admin by Powershell"
$LocalAdmin.SetInfo()
$LocalAdmin.UserFlags = 64 + 65536 # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD
$LocalAdmin.SetInfo()

I have this, but was wondering if there is anything more PowerShell-esque.

asked Mar 1, 2013 at 21:20

PnP's user avatar

4

Another alternative is the old school NET USER commands:

NET USER username "password" /ADD

OK — you can’t set all the options but it’s a lot less convoluted for simple user creation & easy to script up in Powershell.

NET LOCALGROUP "group" "user" /add to set group membership.

Cristian Ciupitu's user avatar

answered May 20, 2013 at 13:02

SinisterPenguin's user avatar

3

As of PowerShell 5.1 there cmdlet New-LocalUser which could create local user account.

Example of usage:

Create a user account

New-LocalUser -Name "User02" -Description "Description of this account." -NoPassword

or Create a user account that has a password

$Password = Read-Host -AsSecureString
New-LocalUser "User03" -Password $Password -FullName "Third User" -Description "Description of this account."

or Create a user account that is connected to a Microsoft account

New-LocalUser -Name "MicrosoftAccountusr name@Outlook.com" -Description "Description of this account." 

answered Sep 12, 2016 at 15:44

codevision's user avatar

codevisioncodevision

4,88736 silver badges48 bronze badges

4

Try using Carbon’s Install-User and Add-GroupMember functions:

Install-User -Username "User" -Description "LocalAdmin" -FullName "Local Admin by Powershell" -Password "Password01"
Add-GroupMember -Name 'Administrators' -Member 'User'

Disclaimer: I am the creator/maintainer of the Carbon project.

answered Jul 10, 2013 at 3:58

Aaron Jensen's user avatar

Aaron JensenAaron Jensen

25.2k15 gold badges79 silver badges88 bronze badges

3

As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):

As much as we might hate to admit it, there are still no Windows
PowerShell cmdlets from Microsoft that permit creating local user
accounts or local user groups. We finally have a Desired State
Configuration (DSC ) provider that can do this—but to date, no
cmdlets.

Slogmeister Extraordinaire's user avatar

answered Jun 12, 2015 at 20:49

rasx's user avatar

rasxrasx

5,2162 gold badges45 silver badges58 bronze badges

Import-Csv C:test.csv |
Foreach-Object {
  NET USER    $ _.username   $ _.password /ADD
  NET LOCALGROUP "group" $_.username  /ADD
}

edit csv as username,password
and change «group» for your groupname

:) worked on 2012 R2

Piotr Adam Milewski's user avatar

answered Jan 7, 2018 at 0:06

Anderson Abu Soares's user avatar

$sec_pass = ConvertTo-SecureString -String "SomePasword" -AsPlainText -Force
New-LocalUser -Name username -FullName username -PasswordNeverExpires -Password $sec_pass
Add-LocalGroupMember -Group Administrators -Member username

answered May 12, 2022 at 10:35

Papa Smurf's user avatar

Для работы с доменными пользователями в PowerShell уже давно существует множество командлетов, но если вам потребуется управлять локальными пользователями, то здесь основным инструментом по прежнему остается графическая оснастка (lusrmgr.msc) и старая добрая утилита командной строки net.  Тем не менее, в PowerShell все же есть возможность для управления локальными пользователями на компьютерах, не входящих в домен.

Для этого можно воспользоваться интерфейсом ADSI (Active Directory Services Interface), который может применяться как для работы с Active Directory, так и с отдельно стоящими компьютерами.

Рассмотрим несколько наиболее актуальных ситуаций при работе с локальными пользователями

Создание пользователя

Первое, что необходимо сделать с пользователем — это создать его учетную запись. Для этого сначала получаем объект компьютера и помещаем его в переменную:

[adsi]$computer = ″WinNT://SRV1″

Затем с помощью метода Create создаем пользователя с именем LocalAdmin:

$user = $computer.Create(″User″, ″LocalAdmin″)

Устанавливаем флажок для того, чтобы пользователь сменил пароль при входе:

$user.Put(″PasswordExpired″, 1)

Задаем начальный пароль:

$user.SetPassword(″P@$$word″)

И добавляем описание в поле «Description»:

$user.Put(″Description″, ″Local administrator″)

Чтобы все сделанные изменения были применены, необходимо выполнить команду:

$user.SetInfo()

Для проверки можно вывести список пользователей командой:

$computer.Children | where {$_.Class -eq ″user″} | ft name, description -auto

создание нового пользователя

Ну или посмотреть в графической оснастке.

новый пользователь в GUI

А теперь представим, что требуется установить флаги «User cannot change password» иили «Password never expired». Эти настройки хранятся в свойстве пользователя UserFlags, которое представляет из себя битовую маску. Для вычисления необходимого значения используется операция -bor (побитовое ИЛИ), например так мы установим флаг «Password never expired»:

$flag = $user.UserFlags.Value -bor 0x10000
$user.Put(″userflags″,$flag)
$user.SetInfo()

Примечание. Значения, необходимые для установки различных флагов, можно посмотреть на странице http://msdn.microsoft.com/en-us/library/aa772300(VS.85).aspx

Надо иметь в виду, что при установке одного флага остальные сбрасываются. К примеру, если установить флаг «User cannot change password» (значение 0x40), то флаг «Password never expired» будет снят. Для того, чтобы поставить оба флага, необходимо суммировать их значения, например так:

$flag = $user.UserFlags.Value -bor 0x10040
$user.Put(″userflags″,$flag)
$user.SetInfo()

установка флагов пользователя

Также необходимо помнить, что флаги «User cannot change password» и «Password never expired» несовместимы с «User must change password at next logon», поэтому при установке любого из них он снимается. Это очень наглядно видно в графической оснастке.

результат установки флагов в GUI

И еще одна операция, которая обычно производится при создании пользователя — добавление его в группу. Для примера добавим нашего пользователя в группу локальных администраторов:

[adsi]$group = ″WinNT://SRV1/Administrators, group″
$group.Add($user.Path)

Проверить содержимое группы можно такой несложной 🙂 командой:

$members = @($group.psbase.Invoke(″Members″))
$members | foreach {$_.GetType().InvokeMember(″Name″,″GetProperty″, $null, $_, $null)}

добавление пользователя в группу

Редактирование свойств пользователя

Довольно часто встречается ситуация, когда пользователь уже имеется и его надо отредактировать — сменить пароль, добавить в группу и т.п. Первым делом помещаем объект компьютера в переменную и смотрим список локальных пользователей:

[adsi]$computer = ″WinNT://SRV1″
$computer.Children | where {$_.Class -eq ″user″} | ft name, description -auto

вывод списка локальных пользователей

Предположим, требуется сброситьсменить пароль для пользователя LocalAdmin. Помещаем его в переменную:

[adsi]$user = ″WinNT://SRV1/LocalAdmin,user″

Устанавливаем новый пароль:

$user.SetPassword(″newP@$$w0rd″)

Задаем смену пароля при следующем входе:

$user.Put(″PasswordExpired″,1)

и сохраняем изменения:

$user.SetInfo()

сброс пароля пользователя

А теперь передвинем его из группы локальных администраторов (Administrators) в группу пользователей удаленного рабочего стола (Remote Desctop Users). Для этого помещаем обе группы в переменные:

[adsi]$admins = ″WinNT://SRV1/Administrators,group″
[adsi]$rdpusers = ″WinNT://SRV1/Remote Desktop Users,group″

Затем, используя метод Remove, удаляем пользователя из одной группы:

$admins.Remove($user.Path)

и добавляем в другую с помощью метода Add:

$rdpusers.Add($user.Path)

перемещение пользователя в другую группу

Отключениеудаление пользователя

Ну и конечно может потребоваться отключить или удалить учетную запись пользователя. За отключение отвечает флаг «Account is disabled», который также хранится в UserFlags. Сначала помещаем в переменную значение, соответствующее отключенной записи:

$disabled = 0x0002

Затем с помощью операции -band (побитовое И) проверяем, включена ли учетная запись. Результат выводим в логическом (boolean) виде:

($user.UserFlags.Value -band $disabled) -as [bool]

Если команда вернула False, значит учетная запись активна. Задаем новое значение флага:

$flag = $user.UserFlags.Value -bor $disabled

И изменяем текущее значение:

$user.Put(″userflags″, $flag)
$user.SetInfo()

Обновляем кэш и еще раз проверяем, включена ли учетная запись:

$user.RefreshCache()
($user.UserFlags.Value -band $disabled) -as [bool]

Теперь команда возвращает True, что означает успешное выключение. Ну а для обратного включения требуются ровно те-же действия, только вместо операции -bor (включающее ИЛИ) используется операция -bxor (исключающее ИЛИ):

$disabled = 0x0002
$flag = $user.UserFlags.Value -bxor $disabled
$user.Put(″userflags″, $flag)
$user.SetInfo()

выключение учетной записи пользователя

Ну и для окончательного удаления пользователя воспользуемся методом Delete:

[adsi]$computer = ″WinNT://SRV1″
$computer.Delete(″user″,$user.Name.Value)

И проверим результат командой:
$computer.Children | where {$_.Class -eq ″user″} | ft name, description -auto

удаление учетной записи пользователя

На этом у меня все о PowerShell и локальных пользователях. Если это вам покажется недостаточным, то более подробно свойства и методы локальных пользователей описаны на MSDN.

Понравилась статья? Поделить с друзьями:

Вот еще несколько интересных статей:

  • Добавление переменной среды windows 10 через командную строку
  • Добавление переменной в path windows 10
  • Добавление папки в исключения брандмауэра windows 10
  • Добавление папки в исключения антивируса windows 10
  • Добавление оснастки в консоль что это windows 10 как отключить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии