Test local user doesn’t exist before creating

Saw a question asking how to Test local user doesn’t exist before creating.  Windows 8 introduced the LocalAccounts module for Windows PowerShell. On Windows 10 1903 it runs in PowerShell v6/7.

There isn’t a Test-Localuser cmdlet but you can attempt to get the user before creation.

function new-user {
     [CmdletBinding()]
     param (
         [string]$username
     )
     if (-not (Get-LocalUser -Name $username -ErrorAction SilentlyContinue)){
         $pwd = Read-Host -Prompt “Password” -AsSecureString
         New-LocalUser -Name $username -Password $pwd
     }
     else {
         Write-Warning -Message “User:$username already exists”
     }
}

The function takes a username as a parameter. Get-LocalUser is used to test if the user exists. If so the warning message is printed. If the user doesn’t exist you’re prompted for the password and New-LocalUser is used to create the account. You could add parameters for full name and description if required. It’s also possible to do something similar with Get-LocalGroup and New-LocalGroup

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s