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

  • Question

  •  

    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 ?

    Sunday, April 1, 2018 6:19 AM