Для управления локальными пользователями и группами в Windows можно использовать встроенный PowerShell модуль Microsoft.PowerShell.LocalAccounts. С помощью этого модуля вы можете создать или удалить локального пользователя, создать новую группу безопасности и добавить в нее пользователей. Этот модуль доступен во всех версиях Windows, начиная с Windows Server 2016 и Windows 10. В предыдущих версиях Windows этот модуль устанавливается вместе с Windows Management Framework 5.1 при обновлении версии PowerShell.
Содержание:
- Создать нового локального пользователя с помощью PowerShell
- Управление локальными пользователями Windows из PowerShell
- Используем PowerShell для управления локальными группам
Полный список командлетов PowerShell в модуле LocalAccounts можно вывести так:
Get-Command -Module 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 при помощи PowerShell командлетов из модуля LocalAccounts.
Ранее для управления локальными пользователями и группами в Windows использовалась графическая оснастка Local Users and Groups Management (
lusrmgr.msc
) и команды
net user
,
net localgroup
.
Создать нового локального пользователя с помощью PowerShell
Чтобы быстро создать нового пользователя, выполните команду:
New-LocalUser -Name "TestUser1" -FullName "Test User" -Description "User for tests"
Укажите пароль для нового пользователя:
Если вы хотите использовать командлет New-LocalUser для автоматического создания новых локальных пользователей из скриптов PowerShell, пароль можно задать заранее в коде скрипта. Строку с паролем нужно преобразовать в формат Secure String:
$pass = ConvertTo-SecureString "WinitP@ss321!" -AsPlainText -Force
New-LocalUser -Name TestUser2 -Password $pass
Чтобы сразу добавить пользователя в группу локальных администраторов, выполните команду:
Add-LocalGroupMember -Group Administrators -Member TestUser2
При создании пользователя можно дополнительно использовать следующие параметры:
-
-AccountExpires
– дату действия учетной записи, при наступлении которого учетная запись будет автоматически отключена (по умолчанию командлет New-LocalUser создает бессрочную учетную запись) -
-AccountNeverExpires
-
-Disabled
– отключить учетную запись после создания -
-PasswordNeverExpires
– неограниченный срок действия пароля -
-UserMayNotChangePassword
– запретить пользователю менять свой пароль
Для создания нового пользователя в домене AD нужно использовать командлет New-ADUser.
Управление локальными пользователями Windows из PowerShell
Чтобы вывести список всех локальных пользователей Windows на текущем компьютере, выполните:
Get-LocalUser
Как вы видите, на компьютере имеется 7 локальных учетных записей, 4 из которых отключены (Enabled=False) (в том числе встроенный администратор Windows).
Чтобы вывести все свойства конкретной локальной учетной записи (аналог комадлета для получения информации о пользователях из AD — Get-ADUser), выполните:
Get-LocalUser -Name ‘root’ | Select-Object *
AccountExpires : Description : Enabled : True FullName : PasswordChangeableDate : 7/20/2022 12:17:04 PM PasswordExpires : UserMayChangePassword : True PasswordRequired : False PasswordLastSet : 7/20/2022 12:17:04 PM LastLogon : 5/15/2023 2:01:48 AM Name : root SID: S-1-5-21-1823742600-3125382138-2640950260-1001 PrincipalSource : Local ObjectClass : User
Обратите внимание на атрибут PrincipalSource. В нем указан тип аккаунта. Это может быть:
- Локальный пользователь Windows (PrincipalSource: Local)
- Учетные записи Microsoft (PrincipalSource: Microsoft Account)
- Учетные записи Azure AD (PrincipalSource: AzureAD)
Чтобы получить значение конкретного атрибута пользователя, например, время последней смены пароля, выполните:
Get-LocalUser -Name ‘root’ | Select-Object PasswordLastSet
Чтобы изменить пароль существующего пользователя, выполните команду:
Set-LocalUser -Name TestUser2 -Password $UserPassword –Verbose
Чтобы установить флаг «Срок действия пароля пользователя не истекает» («Password never expired»), выполните:
Set-LocalUser -Name TestUser2 –PasswordNeverExpires $True
Отключить учетную запись:
Disable-LocalUser -Name TestUser2
Включить пользователя:
Enable-LocalUser -Name TestUser2
Чтобы удалить локального пользователя, выполните:
Remove-LocalUser -Name TestUser2 -Verbose
Используем PowerShell для управления локальными группам
Теперь выведем список локальных групп на компьютере:
Get-LocalGroup
Создадим новую группу:
New-LocalGroup -Name 'RemoteSupport' -Description 'Remote Support Group'
Теперь добавим в новую группу несколько локальных пользователей и группу локальных администраторов:
Add-LocalGroupMember -Group 'RemoteSupport' -Member ('SIvanov','root', 'Administrators') –Verbose
Также вы можете добавить пользователя в группы с помощью следующего конвейера (в этом примере мы добавим пользователя в локальную группу, разрешающую ему удаленный доступ к рабочему столу через RDP):
Get-Localuser -Name TestUser2 | Add-LocalGroupMember -Group 'Remote Desktop Users'
Выведем список пользователей в локальной группе:
Get-LocalGroupMember -Group 'RemoteSupport'
В локальную группу могут быть добавлены не только локальные учетные записи (PrincipalSource – Local), но и доменные аккаунты (domain), учетные записи Microsoft (MicrosoftAccount) и аккаунты из Azure (AzureAD).
Чтобы добавить в локальную группу пользователя из Microsoft или AzureAD, используется такой синтаксис:
Add-LocalGroupMember -Group 'RemoteSupport' -Member ('MicrosoftAccount\[email protected]','AzureAD\[email protected]') –Verbose
Чтобы вывести список локальных групп, в которых состоит конкретный пользователь, выполните следующий скрипт:
foreach ($LocalGroup in Get-LocalGroup)
{
if (Get-LocalGroupMember $LocalGroup -Member 'sivanov' –ErrorAction SilentlyContinue)
{
$LocalGroup.Name
}
}
Чтобы удалить пользователя из группы, выполните:
Remove-LocalGroupMember -Group 'RemoteSupport' –Member 'testuser2'
Для управления локальными пользователями на удаленном компьютере нужно сначала подключится к нему через 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"
Для управления локальными пользователями и группами в Windows можно использовать встроенный модуль PowerShell — Microsoft.PowerShell.LocalAccounts. С помощью этого модуля вы можете создать или удалить локального пользователя, создать новую группу безопасности и добавить в неё пользователей. Модуль доступен во всех версиях Windows, начиная с Windows Server 2016 и Windows 10. В более ранних версиях Windows модуль устанавливается с Windows Management Framework 5.1 при обновлении PowerShell.
Приобрести оригинальные ключи активации Windows всегда можно у нас в каталоге от 1099 ₽
Полный список командлетов PowerShell в модуле 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 при помощи командлетов из модуля LocalAccounts.
Создать нового локального пользователя с помощью PowerShell
Чтобы создать нового пользователя, выполните команду:
New-LocalUser -Name "TestUser1" -FullName "Test User" -Description "User for tests"
Задайте пароль для нового пользователя:
$pass = ConvertTo-SecureString "softcomputers@ss321!" -AsPlainText -Force
New-LocalUser -Name TestUser2 -Password $pass
Чтобы сразу добавить пользователя в группу локальных администраторов, выполните:
Add-LocalGroupMember -Group Administrators -Member TestUser2
При создании пользователя можно использовать дополнительные параметры:
— AccountExpires — задаёт дату истечения срока действия учётной записи, после которой она будет автоматически отключена (по умолчанию командлет New-LocalUser создаёт учётную запись без ограничения по сроку действия).
— AccountNeverExpires — устанавливает, что срок действия учётной записи не истекает.
— Disabled — сразу отключает учётную запись после её создания.
— PasswordNeverExpires — указывает, что пароль не требует регулярной смены и действует неограниченно долго.
— UserMayNotChangePassword — запрещает пользователю изменять свой пароль.
Для создания нового пользователя в домене AD нужно использовать командлет New-ADUser.
Управление локальными пользователями Windows из PowerShell
Чтобы вывести список всех локальных пользователей на текущем компьютере:
Get-LocalUser
Вывести все свойства конкретного локального пользователя:
Get-LocalUser -Name 'root' | Select-Object *
Обратите внимание на атрибут PrincipalSource. В нем указан тип аккаунта. Это может быть:
Локальный пользователь Windows — (PrincipalSource: Local)
Учетные записи Microsoft — (PrincipalSource: Microsoft Account)
Учетные записи Azure AD — (PrincipalSource: AzureAD)
Чтобы получить значение конкретного атрибута, например, время последней смены пароля:
Get-LocalUser -Name 'root' | Select-Object PasswordLastSet
Изменить пароль существующего пользователя:
Set-LocalUser -Name TestUser2 -Password $UserPassword -Verbose
Установить флаг «Срок действия пароля пользователя не истекает»:
Set-LocalUser -Name TestUser2 -PasswordNeverExpires $True
Отключить учётную запись:
Disable-LocalUser -Name TestUser2
Включить учётную запись:
Enable-LocalUser -Name TestUser2
Удалить локального пользователя:
Remove-LocalUser -Name TestUser2 -Verbose
Используем PowerShell для управления локальными группами
Чтобы вывести список локальных групп на компьютере:
Get-LocalGroup
Создать новую группу:
New-LocalGroup -Name 'RemoteSupport' -Description 'Remote Support Group'
Добавить пользователей и группу локальных администраторов в новую группу:
Add-LocalGroupMember -Group 'RemoteSupport' -Member ('SIvanov','root', 'Administrators') -Verbose
Добавить пользователя в локальную группу для RDP доступа:
Get-LocalUser -Name TestUser2 | Add-LocalGroupMember -Group 'Remote Desktop Users'
Вывести список пользователей в локальной группе:
Get-LocalGroupMember -Group 'RemoteSupport'
В локальную группу могут быть добавлены не только локальные учетные записи (PrincipalSource – Local), но и доменные аккаунты (domain), учетные записи Microsoft (MicrosoftAccount) и аккаунты из Azure (AzureAD).
Добавить в локальную группу пользователя из Microsoft или AzureAD:
Add-LocalGroupMember -Group 'RemoteSupport' -Member ('MicrosoftAccount\[email protected]','AzureAD\[email protected]') -Verbose
Скрипт для вывода списка локальных групп, в которых состоит пользователь:
foreach ($LocalGroup in Get-LocalGroup) { if (Get-LocalGroupMember $LocalGroup -Member 'sivanov' -ErrorAction SilentlyContinue) { $LocalGroup.Name } }
Удалить пользователя из группы:
Remove-LocalGroupMember -Group 'RemoteSupport' -Member 'testuser2'
Управление локальными пользователями на удалённом компьютере
Подключитесь к удалённому компьютеру через WinRM командлетами Invoke-Command или Enter-PSSession. Пример команды для сбора списка учётных записей в локальной группе на удалённых компьютерах:
$s = New-PSSession -ComputerName pc01,pc02,pc03
Invoke-Command -ScriptBlock {Get-LocalGroupMember -Group 'RemoteSupport'} -Session $s -HideComputerName | Select * -ExcludeProperty RunspaceID | Out-GridView -Title "LocalAdmins"
Эти команды и скрипты помогут эффективно управлять пользователями и группами в Windows с использованием PowerShell, позволяя автоматизировать выполнение административных задач и повысить безопасность сети.
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 |
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"
Note
PowerShell 7.3.x throws an error “New-LocalUser: Could not load type ‘Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI’” , you can solve it by first importing the localaccounts module with:
import-module microsoft.powershell.localaccounts -UseWindowsPowerShell
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 = "\\server\folder\log.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 = "\\server\folder\log.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.
In this tutorial, I will explain how to create local user accounts in Windows using PowerShell. PowerShell provides a quick and easy way to automate the process of creating new users. I recently needed to set up several new employee accounts on Windows PCs in our office, so I used PowerShell to speed things up.
Note: I used Windows PowerShell ISE to execute all the PowerShell scripts.
Create a New Local User with New-LocalUser in PowerShell
The simplest way to create a new local user in Windows in PowerShell is with the New-LocalUser
cmdlet. Here’s an example of creating a new user named “John Smith”:
New-LocalUser -Name "John Smith" -Description "Sales Associate" -NoPassword
This creates a new local user account named “John Smith” with the description “Sales Associate”. The -NoPassword
switch specifies that no password is required for the account initially.
You can also specify a password for the new account:
$Password = Read-Host -AsSecureString
New-LocalUser -Name "Amy Johnson" -Password $Password -FullName "Amy Johnson" -Description "Marketing Manager"
In this example, we first prompt for the password using Read-Host
and store it as a secure string in the $Password
variable. Then we provide the password when calling New-LocalUser
along with the full name and description for the account.
Check out Create Desktop Shortcuts with Custom Icons Using PowerShell
Add a User to a Local Group using PowerShell
When you create a new local user, you may want to add them to an existing local group to grant the appropriate permissions. You can do this with the Add-LocalGroupMember
cmdlet:
Add-LocalGroupMember -Group "Users" -Member "John Smith"
This adds the local user “John Smith” to the local “Users” group.
Modify Local User Properties in PowerShell
After creating a local user, you can modify properties like the full name, description, password, and more using the Set-LocalUser
cmdlet. For example:
Set-LocalUser -Name "John Smith" -FullName "John W. Smith" -Description "Sales Lead"
This updates the full name and description for the user “John Smith”.
To change the password for a local user:
$NewPassword = Read-Host -AsSecureString
Set-LocalUser -Name "Amy Johnson" -Password $NewPassword
This prompts for a new password and updates the password for the user “Amy Johnson”.
Check out Create a Self-Signed Certificate Using PowerShell
Check if a Local User Exists in PowerShell
Before attempting to create a new local user, you may want to check if a user with that username already exists to avoid an error. Here’s an example and the complete PowerShell script:
$UserName = "John Smith"
if (Get-LocalUser | Where-Object {$_.Name -eq $UserName}) {
Write-Host "The user $UserName already exists."
} else {
Write-Host "The user $UserName does not exist."
New-LocalUser -Name $UserName -NoPassword
}
This script checks if a local user named “John Smith” exists. If so, it outputs a message saying the user already exists. If not, it creates the new user.
Here is the exact output in the screenshot below:
Remove a Local User using PowerShell
To remove a local user account that is no longer needed, use the Remove-LocalUser
cmdlet in PowerShell:
Remove-LocalUser -Name "Amy Johnson"
This deletes the local user account named “Amy Johnson”. Note that you cannot remove an account that is currently logged in.
Conclusion
PowerShell provides a variety of cmdlets for managing local users in Windows. You can easily create new users, modify user properties, add users to groups, check if users exist, and remove users as needed. Using PowerShell to automate these tasks can save a lot of time compared to using the GUI, especially when you need to create multiple accounts.
The key cmdlets to remember are:
New-LocalUser
– Create a new local user accountSet-LocalUser
– Modify properties of a local userAdd-LocalGroupMember
– Add a user to a local groupGet-LocalUser
– List local users and check if a user existsRemove-LocalUser
– Delete a local user account
I hope this tutorial helps you understand how to create and manage local Windows users with PowerShell. Let me know if you have any other questions in the comment below:
You may also like:
- Create a Local Admin Account Using PowerShell
- Retrieve Your Windows Product Key Using PowerShell
- Enable WinRM (Windows Remote Management) Using PowerShell
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.
Learn how to Create a user in Windows with PowerShell step by step. Usually most Windows users have accidentally struggled with CMD or Command Prompt at least once and know that CMD or Command Prompt is used to execute Windows commands. But few people know what PowerShell is and how it works. In this article, we will teach you how to create a user in Windows with PowerShell. PowerShell is a tool like Command Prompt that is much more complex and powerful than Command Prompt and is supposed to replace Command Prompt altogether. Because PowerShell’s ability and control over Windows is much greater than Command Prompt.
Note: The CMD or Command Prompt commands work in PowerShell environment, and you can also use the CMD user command to create a PowerShell user.
This tutorial is based on PowerShell version 5.1 and above, which is installed by default on Windows 10 and Windows Server 2016 and above. To use this command in older versions, you must add the relevant module to the PowerShell or use the Command Prompt command to create a user. Join us now to learn how to create a user in Windows with PowerShell.
Table of Contents
Tutorial create a user with PowerShell commands
Windows PowerShell follows a comprehensive structure, and knowing that you have worked with PowerShell will make it very easy to learn how to create a user build in PowerShell.
1- First open PowerShell with Administrator access in Windows.
2- To create a user in PowerShell, the New-localuser command is used, the structure of which is similar to the following.
New-LocalUser -Name [username] [Option]
The structure of the New-LocalUser command is such that it has a main section called Name, which is actually the username and other parameters that we will explain below.
Example to create a user in Windows with PowerShell
Before explaining the various parameters, pay attention to the following two examples to get more familiar with the structure of the user command created in PowerShell.
Example 1:
In the example below, a user named Michael is created and no password is assigned to it, and in the Description section, a description is written for this user that can be customized as you wish.
New-LocalUser -Name “Michael” -Description “Test User” -NoPassword
Example 2:
In the following example, as in the first example, a user with a specific username Michael and Description will be created and assigned a password. The important point in this example is that PowerShell does not accept the password as a simple type or Clear text, and you must first create a variable and enter the password in it, and then use the variable between commands.
Enter the following command to create a variable called Password and receive it from you secretly.
$password = Read-Host -AsSecureString
After entering the above command, you will receive a password. After pressing Enter, you can also use the following command.
New-LocalUser -Name “Michael” -Description “Test User with Password” -Password $password
This will allow you to create a user in PowerShell. We will now go on to describe the other practical parameters mentioned.
New-LocalUser command parameters in PowerShell
AccountExpires: The user’s expiration date is specified by this parameter
AccountNeverExpires: User account expired or not
Disabled: The user account is active or inactive
FullName: Full username
PasswordNeverExpires: User password expires or not
UserMayNotChangePassword: The user can change the password or not
The items mentioned are important parameters of this command, which along with the parameters mentioned in the first and second examples, together constitute the practical and specific parameters of this command.
Below is a complete example of creating a user. In this example, see the use of parameters.
New-LocalUser -Name “Michael” -Description “IT Manager” -Password $password -FullName “Michael Jordan-Disabled -PasswordNeverExpires –UserMayNotChangePassword
Conclusion
We tried to teach you how to create a user in Windows with PowerShell with practical examples. It was also mentioned New-LocalUser command parameters in PowerShell.