Exchange command works in shell, but not in script

In one of my scripts, I have a command to set the Out of Office message for a user. The command works when I type it in to an Exchange Management Shell window, but not within a script run from the EMS. I am using Exchange 2013.

Set-MailboxAutoReplyConfiguration $username -AutoReplyState enabled -ExternalAudience all -InternalMessage “$ooo” -ExternalMessage “$ooo”

It works in the shell. When I run it in the script I get this error:

Set-MailboxAutoReplyConfiguration : Cannot find information about the local server ( in Active Directory.
This may be related to a change in the server name.

Why is this happening?

So, to be clear, you can manually type the command in the EMS and it works, but if you place the same command in a text file, and run it from the same EMS window, it doesn’t work?

Not exactly.
If I put those commands in a .ps1 file and call the script as such:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psconsolefile “C:\Program Files\Microsoft\Exchange Server\V15\Bin\exshell.psc1” -file “C:\Scripts\termination\termination.ps1”

it does not work.


So, that suggests something about the shell you’re launching that way, as set up by the .psc1 file, isn’t the same as the shell where you’re manually running the command. Without sitting in front of your computer it’s a little tough to tell what that might be, but it’s where I’d start looking.

Also, make sure that the console window - when you launch it using that command you shared - has appropriate permissions. For example, if it doesn’t say “Administrator,” then it isn’t running under Administrator credentials. It might be necessary to use RunAs.exe to start the shell, depending on how security is set up in your environment.

You’re on to something. The shortcut for the EMS that works is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". ‘C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1’; Connect-ExchangeServer -auto -ClientApplication:ManagementShell "

But the shortcut for the script is:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -psconsolefile “C:\Program Files\Microsoft\Exchange Server\V15\Bin\exshell.psc1” -file “C:\Scripts\termination\termination.ps1”

Now I just need to figure out how to get “RemoteExchange.ps1” working with my script…

I dumped the contents of ‘C:\Program Files\Microsoft\Exchange Server\V15\bin\RemoteExchange.ps1’ in to my script and it worked. Not the best solution, but it will hold me over until I find a better fix.

Oops, forgot to mark “Resolved”