Powershell AD and Exchange update script RRS feed

  • Question

  • Hi

    I have made a PowerShell script that creates a user in AD and then create the mail contact in Exchange

    Running the script creates the user in AD but the creation in Exchange is running in its own session due to needed authentication and to me it looks like the script is not waiting for the Exchange session to complete before completing.
    Anyone know how to do this?

    Running the script for 100 users makes the Exchange sessions pile up and execute slow even though the script is already completed which means that error handling fails

    Br. Jesper

    Thursday, October 3, 2019 10:56 AM

All replies

  • Could you post the script that you are using, also for the error handling part have you set ErrorAction to Stop?
    Thursday, October 3, 2019 11:12 AM
  • Something like the below

    The ${...} entries are replacement tags


    $ErrorActionPreference = "Stop"
    	$startMs = (Get-Date).Millisecond
    	New-ADUser -Name '${adObjectName}' -AccountPassword (ConvertTo-SecureString -AsPlainText '${adAuth}' -Force) -ChangePasswordAtLogon $false -DisplayName '${adObjectName}' -Enabled $${enabled?c} -PasswordNeverExpires $true -SamAccountName '${samAccountName}' -UserPrincipalName '${userPrincipalName}' -Path '${ldapPath}' -OtherAttributes @{ExtensionAttribute1='${uuid}'} -EmailAddress '${email}' 
    	$user = '${exchangeUserName}'
    	$password = ConvertTo-SecureString '${exchangeUserPwd}' -AsPlainText -Force
    	$credential = New-Object System.Management.Automation.PSCredential ($user, $password)
    	$mailSessionError = $null
    	$sessionOption = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
    	$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'http://${exchangehostName}/PowerShell/' -Authentication Kerberos -Credential $credential -AllowRedirection -SessionOption $sessionOption
    	Import-PSSession $session -DisableNameChecking -AllowClobber -CommandName New-MailContact,Get-MailContact,Set-MailContact,Add-DistributionGroupMember
    	try {
    		New-MailContact -Name '${adObjectName}' -ExternalEmailAddress '${email}' -DisplayName '${adObjectName}' -OrganizationalUnit '${mailOrganizationalUnit}' -alias '${uuid}'
    		Get-MailContact -Filter {alias -eq '${uuid}'} | Set-MailContact -CustomAttribute1 '${uuid}'
    		Add-DistributionGroupMember -Identity '${mailDistributionGroup}' -Member '${mailOrganizationalUnit}/${adObjectName}'
    	} catch {
    		$mailSessionError = $error
    	Remove-PSSession $session
    	$session = $Null
    	if ($mailSessionError -eq $null) {
    		write-host '${EXEC_SUCCESS_STATE_VALUE}'
    	} else {
    		write-host '${EXEC_ERROR_STATE_VALUE}: '
    		write-host $mailSessionError
    	write-host '${EXEC_ERROR_STATE_VALUE} Exception: '
    	write-host $_
    finally {
    	if ($session -ne $Null) {
    		Remove-PSSession $Session
    	$stopMs = (Get-Date).Millisecond
    	$diff = $stopMs - $startMs
    	write-host ('Script execution time {0} ms' -f $diff)


    Thursday, October 24, 2019 7:36 AM
  • Yes the above should work.
    Thursday, October 24, 2019 10:52 AM
  • Yes. It is working, but the issue here is that it looks like the script does not wait for the remote PSSession to complete before returning. Firing 300 scripts of the in separate threads results in the remote sessions to pile up and I can see a powershell windows process running for ½ hour after all scripts has returned

    Therefore it looks like the remote PSSession runs in a separate thread in windows and is queued up.

    How do I prevent this from happening?

    Br. Jesper

    Monday, November 4, 2019 11:44 AM