Hello,
In the provided script, the try and finally blocks are missing. The Set-Mailbox cmdlet is executed on the mailbox of the user the custom command is running on. Hence, there is no need to use the $mailbox variable. The %distinguishedName% value reference can be used instead. Also, there is no need to execute the Set-Mailbox cmdlet twice, both parameters can be set in a single call of the cmdlet. Please, find the updated script below.
$exchangeServer = "servername.domain.com" # TODO: modify me
try
{
# Connect to Exchange server
$session = New-PSSession -connectionURI "http://$exchangeServer/powershell" -ConfigurationName Microsoft.Exchange
Import-PSSession -session $session -CommandName "Set-Mailbox"
# Set commands against the mailbox
Set-Mailbox -Identity "%distinguishedName%" -MessageCopyForSendOnBehalfEnabled $true -MessageCopyForSentAsEnabled $true
}
finally
{
# Close the remote session and release resources
if ($session) { Remove-PSSession -Session $session}
}