microsoft_windows:adduser_powershell
This is an old revision of the document!
Add/Update User with PowerShell
We needed a way to automatically update a local user on a bunch of systems which were not on an Active Directory configuration. We had remote access, and the ability to run PowerShell scripts as an administrator.
It should not be interactive at all.
The first step is to generate a password hash (what Windows callas a SecureString) so we are not passing around passwords in plaintext.
- genPass.ps
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force $plain = convertFrom-securestring -securestring $password $plain
The final line will give a very long hex number, which is the hash of the password (“password” in first line). Paste that where the script has “Very Long Hex String from above” (keep the quotes around it). Adjust username and/or group, then simply run the script in powershell with admin rights.
- adduser.ps
# script to add a local user with admin privileges on a Windows machine # Generate the password hash with the following three lines (after changing "password" # # $password = ConvertTo-SecureString -String "password" -AsPlainText -Force # $plain = convertFrom-securestring -securestring $password # $plain # # paste the output into -String below # adjust the user and which group to add them to. # if user already exists, will ignore (with message. # password is updated no matter what # if user is already in group, will ignore (with message) $password = ConvertTo-SecureString -String "Very Long Hex String from above" $user = 'test' $group = "Administrators" # Check if user exists if (-not (Get-LocalUser -Name $user -ErrorAction SilentlyContinue)) { try { New-LocalUser -Name $user -Password $password -FullName 'Test Account' -Description 'Test Account' -PasswordNeverExpires Write-Host "User '$user' created." } catch { Write-Warning "Failed to create user '$user': $_" } } else { Write-Host "User '$user' already exists." } # Set (or reset) the password try { Set-LocalUser -Name $user -Password $password Write-Host "Password updated for user '$user'." } catch { Write-Warning "Failed to update password: $_" } # Add to local group if not already a member try { if (-not (Get-LocalGroupMember -Group $group -Member $user -ErrorAction SilentlyContinue)) { Add-LocalGroupMember -Group $group -Member $user Write-Host "User '$user' added to group '$group'." } else { Write-Host "User '$user' is already in group '$group'." } } catch { Write-Warning "Failed to add user '$user' to group '$group': $_" }
microsoft_windows/adduser_powershell.1747352374.txt.gz · Last modified: 2025/05/15 18:39 by rodolico