There are two parts to this question.
$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.
CASE 1
CASE 2
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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With