0 votes

I am trying to make a Custom Command to run a PowerShell script - the script will set two variables in Office365:

        Set-Mailbox "%userPrincipalName%" -ForwardingSmtpAddress $Null
        Set-Mailbox "%userPrincipalName%" -DeliverToMailboxAndForward $False

In the PowerShell ISE, I can successfully run the following code to update them:

$Cred = Get-Credential
$s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic –AllowRedirection
Set-ExecutionPolicy RemoteSigned
Import-PSSession $s -AllowClobber

Set-Mailbox <<UPN GOES HERE>> -ForwardingSmtpAddress $Null
Set-Mailbox <<UPN GOES HERE>> -DeliverToMailboxAndForward $False

But I am not sure how to use our Adaxes service account to do this work as a Custom Command; running the code "as-is" yields the following failure (when run against the "3JakeTEST" account):

3JakeTEST (Company.A.org\Disabled\Users)
Remove External Email Forwarding: 1 operation executed
-Run PowerShell script 'sets attributes for external forwarding to $Null' for the user
--Cannot process command because of one or more missing mandatory parameters: Credential.

What can I use to establish the connection to our Office365 instance, using the default credentials that our other scripts use?

All help is appreciated!

by (150 points)
0

Additional info:

THIS script, provided by Adaxes, uses a different method of authenticating (to the LyncOnlineConnector):

http://www.adaxes.com/script-repository ... e-s288.htm

This DOES work in our environment (as a Production Script instead of a Custom Command). I tried updating it to connect to MSOnline instead, and then run the two lines of code, like this:

# Get the user ID in Office 365
try
{
    $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    $Context.LogMessage("The user doesn't have an Office 365 Account", "Warning")
    return
}

# Script block to remove FWD from the user
$scriptBlock = {
    Import-Module MSOnline      #<<---------------------------------#

    # Connection to Office365
    $password = ConvertTo-SecureString -AsPlainText -Force -String $password
    $credential = New-Object System.Management.Automation.PsCredential($adminName,$password)

    try
    {
        # Connect to O365
        $session = New-CsOnlineSession -Credential $credential
        Import-PSSession $session -AllowClobber | Out-Null

        # Break the external FWD
        Set-Mailbox "%userPrincipalName%" -ForwardingSmtpAddress $Null
        Set-Mailbox "%userPrincipalName%" -DeliverToMailboxAndForward $False
    }
    finally
    {
        # Close the remote session and release resources
        Remove-PSSession $session
    }
}

# Get credential to connect to Office 365 with
$office365Cred = $Context.GetOffice365Credential()
$adminName = $office365Cred.Username
$password = $office365Cred.GetNetworkCredential().Password

# Start Windows PowerShell as a separate process and run the script block in that process
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$arguments = @("-noninteractive", "-noprofile", "-executionpolicy bypass", "-Command `$adminName = '$adminName'; `$password = '$password'; `$objectId = '$objectId'; `$policyName = '$policyName'; $scriptBlock")
$starProcessInfo = New-Object System.Diagnostics.ProcessStartInfo
$starProcessInfo.FileName = $powershellPath
$starProcessInfo.Arguments = $arguments
$starProcessInfo.WindowStyle = "Hidden"
$starProcessInfo.CreateNoWindow = $True
$starProcessInfo.UseShellExecute = $False
$starProcessInfo.RedirectStandardOutput = $True 
$starProcessInfo.RedirectStandardError = $True
$process = [System.Diagnostics.Process]::Start($starProcessInfo)
$resultErrors = $process.StandardError.ReadToEnd()
$resultOutput = $process.StandardOutput.ReadToEnd()

# Add operation result to the Execution Log
# Add errors
if (-not([System.String]::IsNullOrEmpty($resultErrors)))
{
    $Context.LogMessage($resultErrors, "Error")
}

# Add information messages and warnings
if (-not([System.String]::IsNullOrEmpty($resultOutput)))
{
    $Context.LogMessage($resultOutput, "Warning")
}

This returns the error:

3JakeTEST (Company.A.org\\Disabled\\Users)  
 -Remove External Email Forwarding: 1 operation executed  
 --Run PowerShell script 'sets attributes for external forwarding to $Null' for the user  
 Set-Mailbox : The term 'Set-Mailbox' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again...

I thought that Set-Mailbox was part of the MSOnline module; is there a different module I should try to import instead?

1 Answer

0 votes
by (270k points)
selected by
Best answer

Hello Jake,

To achieve this, you do not need a script. You can do it using our built-in Modify Exchange properties action. To add the action to your Custom Command, Business Rule or Scheduled Task:

  1. Select Modify Exchange properties.
  2. Click Exchange properties button.
  3. Activate the Mailbox Features tab and select Modify Delivery Options.
  4. Select Forwarding Address.
  5. Click OK three times and save the changes.
0

Thanks Support2,

My understanding from our Microsoft Premier Support rep is that there are two different fields; one can be used only for internal forwarding, but must be chosen from the organization's Global Address List. This is the one that would be updated by the native functionality shown above. That mailbox attribute is "ForwardingAddress".

The OTHER attribute can be used to set up forwarding OUTSIDE the organization and is just a free-text field (so it gives the user the ability to forward all email to an external address like Gmail, etc.). That attribute is "ForwardingSmtpAddress" and I did not find any native functionality in Adaxes to update that field.

We want to add a step to our user offboarding process that "breaks" any external forwarding when a person leaves. It seems pretty simple to run this through the ISE, but I'm having trouble getting it to work as a Custom Command.

This link has some more info about the difference between the two attributes:

https://blogs.technet.microsoft.com/tim ... warding-2/

And this is the script we're using to identify who has their mailboxes forwarded:

https://gallery.technet.microsoft.com/s ... x-959f4ce5

0

Hello Jake,

That attribute is "ForwardingSmtpAddress" and I did not find any native functionality in Adaxes to update that field.

Yes, this property can be set only using PowerShell scripts. In your script the issue was related to getting credentials of the Office 365 tenant. You can use the GetOffice365Credential method to do so. Below is the script that clears external forwarding for a mailbox:

# Get the user ID in Office 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user doesn't have an Office 365 Account", "Warning")
    return
}

try
{
    # Connect to Exchange Online
    $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.outlook.com/powershell/" -Credential $Context.GetOffice365Credential() -Authentication Basic -AllowRedirection
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName Set-Mailbox

    # Set forwarding parameters
    Set-Mailbox $objectId -ForwardingSmtpAddress $NULL -DeliverToMailboxAndForward $False
}
finally
{
    if ($session) { Remove-PSSession $session}
}
0

That was the answer, thanks Support2 - we have a couple of other projects where making a connection to O365 will be needed, so this authentication method will be useful to us in other situations as well.

As always, you folks are the best - I appreciate your help!

FYI to anyone interested - Our MS Premier Support rep recommended inactivating auto-forwarding like this:

In the Exchange Admin Console:

Mail Flow > Remote Domains > (select the domain to update) > Edit > uncheck "Allow automatic forwarding"

They also recommended unchecking "Allow automatic replies", because a user could set an autoreply to "respond with the text XXXX and forward the email to UnwiseDestination@OutsiteAddress.com".

Our rep also went on to suggest that in cases where Bad Actors have compromised an account, one common action they take is to set up this email forwarding in an effort to gather more information about the compromised person and the company. Disabling this at the top can help minimize the impact of a compromised user account.

I don't claim to be an expert at O365 administration, just passing on what seems like good advice. Be sure to evaluate any global change with your own organization before applying! :mrgreen:

0

Will this script also work to set mail forwarding to a internal user in office 365?

Related questions

0 votes
1 answer

I'm looking at this onliner Set-AdmUser -Identity $DN -Replace @{AADPHoto = $photoBytes} -AdaxesService localhost -Server. I get an illegal operation error. Wondering what I ... the photo in AD and Azure at the same time to avoid waiting for synchronization.

asked Jan 30 by mightycabal (1.0k points)
0 votes
1 answer

I have been searching your site, but could not find a list of access rights needed. --- Morten A. Steien

asked Feb 23, 2021 by Morten A. Steien (300 points)
0 votes
1 answer

Hi, is it possible to export automatically the exchange online mailbox of a user to a .PST file on our archive server before the user is deleted? Kind regards, Fabian

asked Oct 26, 2023 by fabian.p (150 points)
0 votes
1 answer

We created a Scheduled Task and chose our user organisational unit as the activity scope. Then we realized that only about 10 % of the users are object-type: user and 90 % object- ... s no option in adaxes. But there is one for the object type User. Why that ?

asked Dec 5, 2019 by PGstoehl (100 points)
0 votes
1 answer

The built in functionality to convert exchange online mailboxes to shared does not work for users that are synced from our local AD via Azure AD connect. How can we over ... account to in cloud from synced with AD all our issues with this would be resolved.

asked Jul 31, 2019 by john.morrow (270 points)
3,326 questions
3,026 answers
7,727 comments
544,681 users