Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a local user account/ group exists or not with Powershell

Tags:

powershell

There are two parts to this question.

  1. I want to check if a local user exists or not before I go ahead and create it. So far I've come up with a simple script to check if a local user exists or not. Here's the script to check if a user exists before I go ahead and create it.
$password = ConvertTo-SecureString -String "password" -AsPlainText -Force
$op = Get-LocalUser | Where-Object {$_.Name -eq "testuser1"}
if ( -not $op)
 {
  New-LocalUser testuser1 -Password $password | Out-Null
 }

I tested this one out on my setup and it works fine for the most part without throwing any exception. Is there a better, quicker way to check if a user exists ? Also, is the script I'm using foolproof i.e. would it be better to handle it using ErrorAction or using try....catch ?

I'll be using this script for checking more than a couple of user accounts before I go ahead and create them.

  1. Why is $op different in the following cases ?

CASE 1

enter image description here

CASE 2

enter image description here

I understand that Out-String is the reason behind this difference in output but I would've expected the output to have been more than just testuser1 in CASE 1.

I'm new to Powershell so can someone please help me understand why there's a difference in output ?

like image 543
Dhiwakar Ravikumar Avatar asked Apr 01 '18 05:04

Dhiwakar Ravikumar


1 Answers

Use Try/Catch, most of the time it's faster to just ask and let Powershell handle the searching ;)

Especially with Long User lists, retrieving all the users and then iterating trough all of them will slow things down, just asking for a specific user is much faster but you need to handle the error if the user does not exist.

See example below:

Clear-Host
$ErrorActionPreference = 'Stop'
$VerbosePreference = 'Continue'

#User to search for
$USERNAME = "TestUser"

#Declare LocalUser Object
$ObjLocalUser = $null

try {
    Write-Verbose "Searching for $($USERNAME) in LocalUser DataBase"
    $ObjLocalUser = Get-LocalUser $USERNAME
    Write-Verbose "User $($USERNAME) was found"
}
catch [Microsoft.PowerShell.Commands.UserNotFoundException] {
    "User $($USERNAME) was not found" | Write-Warning
}
catch {
    "An unspecifed error occured" | Write-Error
    Exit # Stop Powershell! 
}

#Create the user if it was not found (Example)
if (!$ObjLocalUser) {
    Write-Verbose "Creating User $($USERNAME)" #(Example)
    # ..... (Your Code Here)
}

About outputting certain data, I recommend that you explicitly define what you want to output, this way their will be no surprises and it makes thing clearer in your code.

See the example below, I explicitly defined the 3 properties I wanted and then forced it into a Table-View, to finish I converted it to a string, so no surprises for me any more ;)

Get-LocalUser | Select Name, Enabled, PasswordLastSet | Format-Table | Out-String

Example output

Name               Enabled PasswordLastSet    
----               ------- ---------------    
Administrator        False                    
DefaultAccount       False                    
Gast                 False                    
Test-Gebruiker        True 24-12-2017 01:58:12
like image 81
SteloNLD Avatar answered Oct 02 '22 12:10

SteloNLD