CrumBum CrumBum - 3 months ago 14
PowerShell Question

creating local account from csv but how to omit already created accounts?

I need to tweak this script to Create a batch of local users from a CSV but skipping an already made account. I can create just fine but how to I omit the local accounts that already exist

$computer = $Env:ComputerName
$text = "C:\accounts.csv"
$user = import-csv -path $text
foreach($strUser) in $user)
{
$user = $struser.user
$password = $struser.password
$description = $struser.description
$group = $struser.group
Clear-Host
$ObjOU = [ADSI]"WinNT://$computer"
$objUser = $objOU.Create("User", $user)
$objUser.setpassword($password)
$objUser.put("description",$description)
$objUser.SetInfo()
$objGroup = [ADSI]"WinNT://$computer/$group"
$objGroup.add("WinNT://$computer/$user")
$objGroup.SetInfo()
}

Answer
#setting Variables 
$computer = $Env:ComputerName
$text = "C:\ProgramData\Bridge Operators.csv"
$user = import-csv -path $text
foreach($strUser in $user)
{
 $user = $struser.user
 $password = $struser.password
 $description =  $struser.description
 $group = $struser.group
 Clear-Host  
##First check if user exists
$objComputer = [ADSI]"WinNT://$computer,computer"
$colUsers = ($objComputer.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name)
$userFound = $colUsers -contains $user
if (! $userFound) {
  write-host "The $user account did not exist."
  write-host "Creating $user"
 $ObjOU = [ADSI]"WinNT://$computer"
 $objUser = $objOU.Create("User", $user)
 $objUser.setpassword($password)
 $objUser.put("description",$description)
 $objUser.SetInfo()
 $objGroup = [ADSI]"WinNT://$computer/$group"
 $objGroup.add("WinNT://$computer/$user")
 $objGroup.SetInfo()
}
else {
  write-host "$user account exists."
  write-host "skipping"
 }}