PowerShell Script to Create User Account Easily
New-LocalUser -Name 'username' -Password (ConvertTo-SecureString 'password' -AsPlainText -Force) command in PowerShell to create a new local user account with a specified password.Examples
How to Think About It
New-LocalUser cmdlet handles the creation of the account with these details.Algorithm
Code
$password = ConvertTo-SecureString 'MyP@ssw0rd' -AsPlainText -Force New-LocalUser -Name 'NewUser' -Password $password Write-Output "User 'NewUser' created successfully."
Dry Run
Let's trace creating user 'NewUser' with password 'MyP@ssw0rd' through the script
Convert password to secure string
Input: 'MyP@ssw0rd' -> Output: SecureString object
Create new local user
Command: New-LocalUser -Name 'NewUser' -Password
Print confirmation
Output: User 'NewUser' created successfully.
| Step | Action | Value |
|---|---|---|
| 1 | Convert password | MyP@ssw0rd -> SecureString |
| 2 | Create user | Name='NewUser', Password= |
| 3 | Output message | User 'NewUser' created successfully. |
Why This Works
Step 1: Password Conversion
The password must be converted to a SecureString because New-LocalUser requires a secure password format for safety.
Step 2: User Creation
The New-LocalUser cmdlet creates the user account with the given name and secure password.
Step 3: Confirmation Output
A message is printed to confirm the user was created successfully, helping the user know the script worked.
Alternative Approaches
Import-Module ActiveDirectory New-ADUser -Name 'ADUser' -AccountPassword (ConvertTo-SecureString 'Pass123!' -AsPlainText -Force) -Enabled $true
net user NewUser MyP@ssw0rd /add
Complexity: O(1) time, O(1) space
Time Complexity
Creating a single user account is a constant time operation, so it is O(1).
Space Complexity
The script uses a fixed amount of memory for the password and user creation, so space complexity is O(1).
Which Approach is Fastest?
Using New-LocalUser is efficient and secure for local accounts; net user is faster but less secure; Active Directory methods depend on network and permissions.
| Approach | Time | Space | Best For |
|---|---|---|---|
| New-LocalUser cmdlet | O(1) | O(1) | Local user creation with security |
| Active Directory Module | O(1) | O(1) | Domain user creation in AD environments |
| net user command | O(1) | O(1) | Quick local user creation without PowerShell |