powershellexchange-server-2010

How to run exchange powershell command automatically from batch file


I have a .bat file with the following code:

START C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

The code above will successfully start a new powershell host and then connect to my exchange server.

How can I run the below command in the exchange powershell host, from the same batch file? (basically I am trying to automate the process)

Get-MessageTrackingLog -resultsize unlimited -start "01/01/2020 00:00:00" -Server hermod -EventId Deliver | where {[string]$_.sender -like '*@gmail.com'} | where {[string]$_.Recipients -like '*@gmail.com'} > "C:\MailReporter\Output\emails.txt"

Solution

  • I worked it out: I needed to use the ; symbol after the first command to signal the end of the current command. I was then able to execute the next command without issue.

    Full working code:

    START C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Get-MessageTrackingLog -resultsize unlimited -start '01/09/2019 00:00:00' -Server hermod -EventId Deliver | where {[string]$_.sender -like '*@gmail.co.uk'} | where {[string]$_.Recipients -like '*@gmail.co.uk'} > 'C:\MailReporter\Output\emails.txt' "