Errors in Powershell Script That Creates AD Account and Mailbox

Hi,

I've started learning Powershell in an attempt to automate a lot of things that I do as a sys admin. One of the things is to create AD accounts and mailboxes. The script below is the one I use however I get a lot of errors sometimes with it.

# Add Modules and Snap Ins
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue
Import-Module ActiveDirectory -ErrorAction SilentlyContinue

#Check if a data file exists
if (Test-Path c:\ExchangeUserDrop\NewUKUser.csv){

	# Import the CSV data file
	$userList = Import-CSV c:\ExchangeUserDrop\NewUKUser.csv

    # General Variables
    # Work Out Database with most amount of space free
    $db = (Get-MailboxDatabase -Status -Server c6132 | Sort-Object AvailableNewMailboxSpace | Select-Object -Last 1).Name.ToString()
    
    # AD Lookup on for Manager
    $mgr = (Get-QADUser $UserList.Manager | Select DN).DN.ToString()

	# do this for each user
	foreach($user in $UserList){

		# Create some derived values
		$fullName = $User.FirstName + " " + $User.Surname
		$displayName = $User.Surname +", "+ $User.FirstName
		$password = ConvertTo-SecureString -string $user.company -asPlainText -Force
		$UPN = $user.UserName + "@UK01.apmn.org"

		# Check if a user Exists first
		if(Get-User $user.UserName -erroraction 'silentlycontinue'){
			# Just mail enable user account
			Enable-Mailbox $user.UserName
		}	
		else{

			# Make the new mailbox and user account
			New-Mailbox -Name $displayName -UserPrincipalName $UPN -Password $password -Alias $user.UserName -DisplayName $displayName -FirstName $user.FirstName -LastName $user.Surname -OrganizationalUnit $user.ou -Database $db
		}

        # Update AD details
            #Set free text variables
                   Set-User -Identity $user.UserName -Department $user.Department -Title $user.Title -City $user.City -State $user.state -PostalCode $user.zipcode -AssistantName $user.assistant -Phone $user.phone

            #Set non-free text variables
                   Set-User -Identity $user.UserName -MobilePhone $user.mobilephone -Company $user.Company -StreetAddress $user.Address

                   Set-ADUser -Identity $user.UserName -Country UK
                   
            #Set QAD values
                   Set-QADUser -Identity $user.UserName -StreetAddress $user.Address -Office $user.office -Company $user.company -Manager $mgr -Description $user.Description
                   
		# Set Mailbox Custom Attribute and MaxSendSize Limit
		Set-Mailbox $user.UserName -CustomAttribute1 $User.CustomAttribute -MaxSendSize 20MB

		# Set Active Sync Policy
		Set-CASMailbox $user.UserName -ActiveSyncMailboxPolicy(Get-ActiveSyncMailboxPolicy "UKCambrg_ActiveSyncPolicy").Identity
		
	}
	
	# Now delete the CSV file.
	Remove-Item c:\ExchangeUserDrop\NewUKUser.csv

# Summary
Write-Host ""
write-Host ""
Write-Host "Database used for the new Mailbox was $db"
Write-Host "All actions completed."
}

Open in new window

1. The problem/question is how do I do it so that if a value in the csv file is empty then its just skipped and no error is displayed on the shell? As a side question to this, would it be possible to just export this error into a log then email the log to an email address?

2. I also get an error at the end of the script often saying that it cant remove the csv file as its being used in another process. What process would I need to set before that command to kill so that it always deletes it?

3. When the script starts creating the user it displays all the information about the user that its setting (which I'm guessing is one of the Quest addons. Is there a way to hide the display for this as I'm not interested in seeing it? I've read about the [void] prefix but that doesn't seem to help.

Thanks a lot in advance.
simonwebbAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
1. You can put a check into the foreach loop, like
if (!$user.Username) {
  # error part
} else {
  # good part
}

Open in new window

The error part might be
  "The username is empty" | out-file -append C:\temp\logfile.txt

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Qlemo"Batchelor", Developer and EE Topic AdvisorCommented:
2. It cannot be the PowerShell, at least I can't see any reason for it to keep the CSV file open. Maybe it is Excel or a text editor you are viewing the CSV with?

3. The Set-* cmdlets (both of Quest and Exchange) might do the output. You'll need to prefix all of them with [void], or append a   | out-null    or    > nul after each of them.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Windows Server 2008

From novice to tech pro — start learning today.