Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Script to Check for existing user and if not, create new user

$
0
0

Hey,

I am new to Powershell and trying to create an algorithm that creates a new user but only after checking to see if the user exists.

I have looked around online at what others have done and have been playing around with my code, but I can't get the script to run correctly and create a new user.

This is what I have so far...

Any help would be appreciated
--------------------------
#Checking if user exists
Function Get-ADUser {
$Name = "$FirstName $LastName"

$User = Get-ADUser =LDAPFilter"(SAMAccountName=$Name)"
If ($User -eq $Null) {
    return $false
    }
Else {
    return $true
}

#Checking if user exists

Function NewADUser{

Import-Module ActiveDirectoty -ErrorAction SilentlyContinue

    New-ADUser `
    -Name "$FirstName $LastName" `
    -GiveName $FirstName `
    -Surname $LastName `
    -UserPrincipalName "$FirstName.$LastName" `
    -Path "OU=Office Administration_OU,OU=Departments,DC=EC_Bond,DC=com" `
    -AccountPAssword (Read-Host -AsSecureString "Enter Password") -Enabled $true
}

#Adding logic to script
cls
$ch = checkuserExists $NewUserFirstName $NewUserSurname

[string]$NewUserFirstName = Read-Host -Prompt 'Please enter FirstName'
[string]$NewUserSurname = Read-Host -Prompt 'Please enter Surname'

If ($ch) {
    Write-Host "The user you are trying to create already Exists"
    }
    Else {
        [string]$UserCreation = Read-Host -Prompt 'Would you like to create the user [Y] or [N]?'
        If ($UserCreation -eq "Y") {
            NewADUser $NewUserFirstName $NewUserSurname
        }
        Else {
            #Abort process
            Write-Host "Process Aborted"
        }
    }
}


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>