none
Ignore or Skip null values in CopyADUser script RRS feed

  • Question

  • Hi,

    I'm automating a process at work to create a new AD Account if another is copied by using powershell.

    I have that part down but I wanted to use an if else statement or something similar if an account to copy isn't specified then to copy the account of another user (in my example the new user's manager's account with basic details.

    I've tried doing if, elseif, or and ::isnotemptyornull and ::isemptyornull

    The script works if I specify a SAMAccount Name to copy or the manager account to copy but if either used the other throws errors about $null, is there a way that if one of the account instances isn't used then it just ignores the $null value and skips or uses the other one?

    I guess I want the script the work if the SAMAccountName variable is null to fall back and use the 'manageraccount' which is SAMAccount Name of the person who will be their manager however only has basic details (company country, state department).

    This is what I have so far

    #Import AD and Exchange
    Import-Module ActiveDirectory
    #Add-PSSnapin *exchange* #Exchange module required for enabling the mailbox

    #Import VB
    Add-Type -AssemblyName Microsoft.VisualBasic
    $vb = [Microsoft.VisualBasic.Interaction]

    #Variables
    $samaccount_to_copy = $vb::inputbox("Enter SAMAccount Name to Copy")
    $manageraccount = $vb::inputbox("Enter Manager SAMAccount Name")
    $new_displayname = $vb::inputbox("Enter Display Name of new user")
    $new_firstname = ($new_displayname.split(" ")[0])
    $new_lastname = ($new_displayname.Substring($new_displayname.IndexOf(" ") +1))
    $new_samaccountname = ($new_displayname -replace " ",".")
    $new_name = $new_displayname
    $CopyDN = ($ad_account_to_copy.DistinguishedName)
    $Password = 'Password'
    $ManagerDN = ($ad_account_manager.DistinguishedName)
    $CopyPath = ($CopyDN.Substring($CopyDN.IndexOf(',') + 1))
    $ManagerPath = ($ManagerDN.Substring($ManagerDN.IndexOf(',') + 1))
    $enable_user_after_creation = $true
    $password_never_expires = $false
    $cannot_change_password = $false

    $ad_account_to_copy = Get-ADUser $samaccount_to_copy -Properties Description, Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Title, Company, Department, Manager, EmployeeID
    $ad_account_manager = Get-ADUser $manageraccount -Properties Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Company, Department

    #####Check accounts exist#####
    $User = Get-ADUser $samaccount_to_copy -Properties * | Select Name

    If ($samaccount_to_copy -eq $Null) 
    {
        "User doesn't Exist in AD"

    Else 
    {
        "User found in AD"
    }

    $Manager = Get-ADUser $manageraccount -Properties * | Select Name

    If ($manageraccount -eq $Null) 
    {
        "User doesn't Exist in AD"

    Else 
    {
        "User found in AD"
    }

    ##### Create Template of Existing Account to copy from;If no account specified copy basic attrbutes of line manager's account
    If ($samaccount_to_copy) 
    {        

    ## Create the new user account
        New-ADUser -SamAccountName $new_samaccountname -Instance $ad_account_to_copy -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "mcauliffe-systems.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)                     

    Else

         ($mangageraccount)

        New-ADUser -SamAccountName $new_samaccountname -Instance $ad_account_manager -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "mcauliffe-systems.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)

    Else 
    {
        "No Account Specified"
    }

    I've been told if I were to use ($sam_account_to_copy -ne $null -and -$manageraccount -eq $null) for the first instance and ($sam_account_to_copy -eq $null -and $manageraccount -ne $null) for the second instance it's code that does nothng and looks bad so I was wondering how I can achieve this without code that looks bad/does nothing?

    Kind Regards,

    • Moved by Bill_Stewart Wednesday, September 13, 2017 8:59 PM This is not "fix/debug/rewrite my script for me" forum
    Saturday, July 15, 2017 1:00 PM

All replies

  • With if/else the code to execute goes inside the braces.

    Your qy=uestions is too vague.  State what is NOT happening and not what you think you should do or what others may have told you.

    To check any value type variable for null we would do this>

    if($samaccount){
          # variable is not null
    }else{
         # variable IS null
    }

    To cascade filters we would do this:

    if ($user_to_copy) {
    	# create new user from copy
    } elseif($manager_to_copy){
    	# create user by copying manager
    }else{
    	Write-Host 'No manager or user specified'
    	# cannot create user
    }


    You have to spend some time thinking about how the logic works.  We call this a filter because it checks conditions in a specific order and selects the first clause that fully matches and also defaults to no matches.  You can add as many clauses as you need but you must understand the effect of the logical propositions to get it to work as needed.

    There are other better approaches to this but they are technically more challenging to implement for new coders.  Yu can use any instance of an account to crate a new instance.  "New-AdUser takes an "Instance" argument that it will copy  but you must supply new name,SamAccountName,upn, surname, givenname and any other differing properties.  Look at the examples for howto do this.

    $copy = if ($copy = Get-ADUser -Filter "SamAccountName -eq '$usertocopy'" -Properties * ) {
    	# return copy
    	$copy
    } elseif($copy = Get-ADUser -Filter "SamAccountName -eq '$managertocopy'" -Properties * ){
    	# return copy
    	$copy
    }else{
    	Write-Host 'No manager or user specified'
    	# cannot create user no copy returned
    }
    
    if($copy){
    	$copy.Name = 'newname'
    	# other changes
    	New-ADUser -Instance $copy
    }else{
    	Write-Host 'No account was specified.'
    }

    HELP New-AdUser -Parameter Instance


    \_(ツ)_/




    • Edited by jrv Saturday, July 15, 2017 1:34 PM
    Saturday, July 15, 2017 1:24 PM
  • Thank you for that.

    I've used the below as a test and it still doesn't create the account so would I have to add more if($samaccount_to_copy -ne $null) before the below?

    #####Check accounts exist#####
    $User = Get-ADUser $samaccount_to_copy -Properties * | Select Name

    If ($samaccount_to_copy -eq $Null) 
    {
        "User doesn't Exist in AD"

    Else 
    {
        "User found in AD"
    }

    $Manager = Get-ADUser $manageraccount -Properties * | Select Name

    If ($manageraccount -eq $Null) 
    {
        "User doesn't Exist in AD"

    Else 
    {
        "User found in AD"
    }

    ##### Create Template of Existing Account to copy from;If no account specified copy basic attrbutes of line manager's account
    $ad_account_to_copy = if($ad_account_to_copy = Get-ADUser -Filter "SamAccountName -eq $samaccount_to_copy" -Properties Description, Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Title, Company, Department, Manager, EmployeeID)
    {         
        # Create the new user account
        $ad_account_to_copy                         

    Elseif ($ad_account_to_copy = Get-ADUser -Filter "SamAccountName -eq $manageraccount" -Properties Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Company, Department)

        $ad_account_to_copy     

    Else 
    {
        "No Account Specified"
    }
    if($ad_account_to_copy)
    {
        $ad_account_to_copy.Name = $new_samaccountname
        New-ADUser -Instance $ad_account_to_copy -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "domain.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)
    }
    Else
    {
        "No Account Specified"
    }
    • Edited by Rach09 Sunday, July 16, 2017 3:46 AM
    Sunday, July 16, 2017 3:42 AM
  • Please take the time to learn PowerShell basics before continuing. I cannot be any more specific.  Also please learn how to format and post your code correctly as I have demonstrated.

    Reposting the same code does not help you nor will it get you an answer that makes any sense to you.

    From your new post it is clear that you did not understand anything I posted.

    It is never necessary to test against $null, $true or $false.  That is what "if" does.

    By learning the basics of PowerShell you will be able to understand the responses and discussions and you will be able to ask a better question.


    \_(ツ)_/

    Sunday, July 16, 2017 8:07 AM
  • My apologies, I'm new to this forum and I've onlu just worked out how to insert the code

    So what you're sayng if it's not necessary to test against $null then howcome powershell can't just ignore $null and skip to what's validated in the code? I guess my understanding was that if checking for the account and if null then the above coding for specifying if exists or not would be sufficient and I wouldn't need to mention if -ne $null all the time.

    What if I were to use the below:

    #####Check accounts exist#####
    $User = Get-ADUser $samaccount_to_copy -Properties * | Select Name
    
    If ($samaccount_to_copy -eq $Null) 
    {
        "User doesn't Exist in AD"
    } 
    Else 
    {
        "User found in AD"
    }
    
    $Manager = Get-ADUser $manageraccount -Properties * | Select Name
    
    If ($manageraccount -eq $Null) 
    {
        "User doesn't Exist in AD"
    } 
    Else 
    {
        "User found in AD"
    }
    
    ##### Create Template of Existing Account to copy from;If no account specified copy basic attrbutes of line manager's account
    If ($samaccount_to_copy) 
    {        
    
    ## Create the new user account
        New-ADUser -SamAccountName $new_samaccountname -Instance $ad_account_to_copy -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "domain.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)                     
    } 
    Elseif ($mangageraccount)
    { 
         
        New-ADUser -SamAccountName $new_samaccountname -Instance $ad_account_manager -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "domain.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)
    }Else{
        "No Account Specified"
    }
    Would using ErrorAction be a better move?
    -ErrorAction SilentlyContinue



    • Edited by Rach09 Sunday, July 16, 2017 10:11 AM
    Sunday, July 16, 2017 9:44 AM
  • Please look at my code and try to understand how it works.  Until you understand the basics of programming it is not possible to give you an answer.  You are pasting together many things with little understanding of how PowerShell or programming works.

    My example answers all of your  questions but it is up to you to understand it. We cannot give you private lessons.

    Look at the code and try and understand what is happening in each line.  You may have to do a tutorial on basic programming or, at least, on basic PowerShell.


    \_(ツ)_/

    Sunday, July 16, 2017 9:49 AM
  • Hi,

    I'm learning powershell and I've been reading up on the basics. While I am farmiluar with if, else and elseif statements, I am trying to use an if else statement to define a variable as an instance to copy for a user account using New-ADUser.

    Basically I want to specify a user to copy, copy that user to create a new one. If no user is specified then copy the basic attributes of their manager.

    The problem is I've tried using Get-ADUser to get properties and define that as a variable for each account but I can't use those variables (that contain variables) to define another variable if that makes any sense.

    I've even tried converting the variables to strings, hashtables (the problem with hash tables as is my understanding that with New-ADUser anything defined in @{} is -OtherAttributes in AD) and arrays.

    I've tried using $nulls and -Filters as well but I seem to run into errors converting the types to System.Management.ActiveDirectory.ADUser

    This is what I have so far. the only problem is not all properties from either $ad_account_to_copy or $ad_account_manager are copied accross when specifying the instance and only a new account is created.

    #Import AD and Exchange
    Import-Module ActiveDirectory
    
    #Import VB
    Add-Type -AssemblyName Microsoft.VisualBasic
    $vb = [Microsoft.VisualBasic.Interaction]
    
    #Variables
    $samaccount_to_copy = $vb::inputbox("Enter SAMAccount Name to Copy")
    $manageraccount = $vb::inputbox("Enter Manager SAMAccount Name")
    $new_displayname = $vb::inputbox("Enter Display Name of new user")
    $new_firstname = ($new_displayname.split(" ")[0])
    $new_lastname = ($new_displayname.Substring($new_displayname.IndexOf(" ") +1))
    $new_samaccountname = ($new_displayname -replace " ",".")
    $new_name = $new_displayname
    $Password = 'Password'
    $enable_user_after_creation = $true
    $password_never_expires = $false
    $cannot_change_password = $false
    
    #####Check accounts exist#####
    
    if ($samaccount_to_copy) {
        $ad_account_to_copy = Get-ADUser -filter {SamAccountName -eq $samaccount_to_copy} -Properties Description, Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Title, Company, Department, Manager, EmployeeID 
    }
    
    if ($manageraccount) {
        $ad_account_manager = Get-ADUser -filter {SamAccountName -eq $manageraccount} -Properties Office, OfficePhone, StreetAddress, City, State, PostalCode, Country, Company, Department
    }
    #####Create account by copying user or user's manager's basic attributes#####
    $CopyUser = "$samaccount_to_copy"
    
    if($CopyUser.Equals($samaccount_to_copy))
    {
        $CopyAccount = "$ad_account_to_copy"
        $CopyDN = ($ad_account_to_copy.DistinguishedName)
        $CopyPath = ($CopyDN.Substring($CopyDN.IndexOf(',') + 1))
        Write-Host "User has been found in AD, creating new user account using user as instance..."
    }
    elseif($Copyuser.Equals($manageraccount))
    {
        $CopyAccount = "$ad_account_manager"
        $ManagerDN = ($ad_account_manager.DistinguishedName)
        $ManagerPath = ($ManagerDN.Substring($ManagerDN.IndexOf(',') + 1))
        Write-Host "Manager has been found in AD, creating new user account using Manager as instance..."
    } 
    else
    {
        Write-Host 'No manager or user found in AD'
    }
    
    $instance = @{'SamAccountName' = $CopyUser}; 
    New-Aduser -Instance $instance -SamAccountName $new_samaccountname -Name $new_name -DisplayName $new_displayname -GivenName $new_firstname -Surname $new_lastname -PasswordNeverExpires $password_never_expires -CannotChangePassword $cannot_change_password -EmailAddress ($new_samaccountname + '@' + "domain.com") -Enabled $enable_user_after_creation -UserPrincipalName ($new_samaccountname + '@' + "domain.com") -AccountPassword (ConvertTo-SecureString -AsPlainText $Password -Force)

    If anyne could point me in the right direction?

    Kind Regards,



    • Edited by Rach09 Friday, July 21, 2017 1:14 PM remove extra charactors
    • Merged by Bill_Stewart Friday, July 21, 2017 2:18 PM Duplicate
    Friday, July 21, 2017 1:10 PM