How to use Exchange 2010 cmdlet in batch file

2019-07-07 19:17发布

问题:

I can run Get-ActiveSyncDeviceAccessRule correctly in Exchange Management Shell directly. (reference: http://technet.microsoft.com/en-us/library/dd776124.aspx)

Then I wrote a batch file as below, but I got CommandNotFoundException. I'd like to know how I can use this cmdlet with cmd.exe? Could anyone can help me? Thank you.

(Editor's note: The next three lines were wrapped for formatting. Originally 1 line)

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  Get-ActiveSyncDeviceAccessRule >C:\ActiveSyncDeviceAccessRule_output.txt
  2>C:\standardError.txt
echo %errorlevel% >C:\exitCode.txt

And I get error in standardError.txt as below:

The term 'Get-ActiveSyncDeviceAccessRule' 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.
At line:1 char:31
+ Get-ActiveSyncDeviceAccessRule <<<< 
    + CategoryInfo          : ObjectNotFound: (Get-ActiveSyncDeviceAccessRule: 
   String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

回答1:

(Answered by the OP in a question edit. Converted to a community Wiki Answer. See Question with no answers, but issue solved in the comments (or extended in chat) )

The OP wrote:

I've solved my problem. I missed some command to connect the Exchange server. And the cmdlet Get-ActiveSyncDeviceAccessRuleis belong to Exchange Server 2010 SP1. You can find the target command in the properties window of Exchange Management Shell.

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

I updated my batch file as below. And it works.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command ". 
'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; 
Connect-ExchangeServer -auto;Get-ActiveSyncDeviceAccessRule" 
>C:\ActiveSyncDeviceAccessRule_output.txt 2>C:\standardError.txt
echo %errorlevel% >C:\exitCode.txt