PowerShell API-Wrapper Tutorial: Unterschied zwischen den Versionen

[unmarkierte Version][gesichtete Version]
 
(18 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
__NOTOC__
+
{{raw::en:PowerShell API Wrapper Tutorial}}
++ Under construction ++
 
  
Dieses Tutorial erläutert anhand einfacher Beispiele den Umgang mit der [[MailStore Server Administration API]] mittels Windows PowerShell Skripten. Grundlegende MailStore Server, Windows und PowerShell Kenntnisse werden dabei vorausgesetzt.
+
[[de:PowerShell API-Wrapper Tutorial]]
 
+
[[en:PowerShell API Wrapper Tutorial]]
Der im Tutorial verwendete API Wrapper stellt eine Beispielimplementierung eines MailStore Server Administration API Clients dar. Da die Kommunikation mit der Administration API in Form von Web Requests mittels HTTPS erfolgt, können selbstverständlich auch eigene Implementierungen verwendet werden, welche mit entsprechenden PowerShell Cmdlets arbeiten. Diese Möglichkeit wird hier allerdings nicht weiter betrachtet.
 
 
 
<p class=msnote>'''Hinweis:''' Es wird empfohlen, für dieses Tutorial und grundsätzlich für die Skriptentwicklung eine eigene, nicht produktive Installation von MailStore Server in einer Testumgebung zu verwenden, um Probleme und Datenverluste in der Produktivumgebung zu vermeiden. Hierfür eignet sich z.B. die voll funktionsfähige, 30-Tage-Testversion von MailStore Server.</p>
 
 
 
= Installation der benötigten Komponenten =
 
 
 
Die gezeigten Beispiele nutzen den MailStore PowerShell API Wrapper und sind wie dieser auf Windows PowerShell ab Version 3.0 lauffähig. Abhängig von der verwendeten Windows Version muss eine kompatible PowerShell Version zunächst heruntergeladen und installiert werden. Die für das Tutorial benötigten Komponenten finden Sie hier:
 
 
 
* [[Media:MailStorePSAPIWrapper.zip?|MailStore PowerShell API Wrapper]]
 
* [[Media:MailStorePSTutorialScripts.zip?|MailStore PowerShell Tutorial Beispielskripte]]
 
* [http://www.microsoft.com/en-us/download/details.aspx?id=34595 Windows Management Framework 3.0] (enthält die PowerShell 3.0)
 
* [http://www.microsoft.com/de-de/download/details.aspx?id=40855 Windows Management Framework 4.0] (alternativ, enthält die PowerShell 4.0)
 
 
 
Bitte beachten Sie auch die Systemvoraussetzungen und Hinweise zur jeweiligen Version des Windows Management Frameworks.
 
 
 
<p class=msnote><span class=mswarning>'''Wichtiger Hinweis:''' Die Installation eines Windows Management Frameworks wird auf Systemen, welche eine bestimmte PowerShell Version voraussetzen und erweitern, wie beispielsweise Microsoft Exchange Server, nicht unterstützt und kann die Funktion dieser Systeme massiv beeinträchtigen oder zum Erliegen bringen.</span></p>
 
 
 
Nach dem Herunterladen und ggf. der Installation der PowerShell entpacken Sie bitte den MailStore PowerShell API Wrapper und die Beispielskripte (standardmäßig nach ''C:\MailStore Scripting Tutorial\PowerShell\'').
 
 
 
Der MailStore PowerShell API Wrapper und die Beispielskripte sind nicht digital signiert. Daher muss zunächst die Ausführung solcher Skripte in einer administrativen PowerShell Session mittels
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Set-ExecutionPolicy -ExecutionPolicy Unrestricted
 
</source>
 
 
 
zugelassen werden.
 
 
 
= Einbinden des MailStore PowerShell API Wrappers =
 
 
 
Der MailStore PowerShell API Wrapper ist als PowerShell Script Module (''MSS.PS.Lib.psm1'') implementiert und wird daher über sein Manifest (''MSS.PS.Lib.psd1'') per ''Import-Module'' in eine PowerShell Session eingebunden.
 
 
 
Öffnen Sie eine PowerShell Session und binden Sie das API Wrapper Modul mit folgenden Befehl ein:
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Import-Module "C:\MailStore Scripting Tutorial\PowerShell\API-Wrapper\MSS.PS.Lib.psd1"
 
</source>
 
 
 
== Informationen zum MailStore PowerShell API Wrapper abrufen ==
 
 
 
Der MailStore PowerShell API Wrapper stellt einige Funktionen und Variablen zur Verfügung, um gemäß PowerShell Konventionen auf die MailStore Server Administration API zugreifen zu können. Geben Sie folgenden Befehl ein, um Informationen hierüber abzurufen:
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Get-Module MSS.PS.Lib | fl
 
</source>
 
 
 
Mittels der Eigenschaften des Moduls kann man noch detailliertere Informationen abrufen. Beispielsweise gibt
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  (Get-Module MSS.PS.Lib).ExportedVariables
 
</source>
 
 
 
die zur Verfügung gestellten Variablen des Moduls zurück.<br/>
 
Mittels
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Get-Help *MSS*
 
</source>
 
 
 
stellt der MailStore PowerShell API Wrapper für seine Funktionen Inline-Hilfen (nur auf Englisch verfügbar) bereit.
 
 
 
= Verwendung der API Wrapper Funktionen =
 
 
 
Anhand des folgenden Beispielskripts soll die grundlegende Verwendung der MailStore PowerShell API Wrapper Funktionen veranschaulicht werden. Dieses Skript finden Sie im Beispielskriptpaket als ''Example1.ps1''.
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Import-Module 'C:\MailStore Scripting Tutorial\PowerShell\API-Wrapper\MSS.PS.Lib.psd1'
 
  $mssapiclient = New-MSSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -Code JSON -IgnoreInvalidSSLCerts
 
  $return = Invoke-MSSApiCall $mssapiclient "GetServerInfo"
 
  $return | fl
 
</source>
 
 
 
Die Funktion ''New-MSSApiClient'' erstellt ein neues API-Client-Objekt, welches dann für API Calls mittels ''Invoke-MSSApiCall'' verwendet werden. Die im Skript angegebenen Werte für die Parameter ''-Username, -Password, -MailStoreServer, -Port'' und ''-Code'' sind die Standardwerte der Funktion, nur der Schalter ''-IgnoreInvalidSSLCerts'' muss bei Verwendung von nicht-vertrauten Zertifikaten explizit angegeben werden, ansonsten kommt es zu einer Fehlermeldung.
 
 
 
''Invoke-MSSApiCall'' benötigt neben dem API-Client-Objekt einen [[MailStore_Server_Administration_API_Commands|API Befehl]] und ggf. dessen Parameter. Der Befehl ''[[MailStore_Server_Administration_API_Commands#GetServerInfo|GetServerInfo]]'' im Skript benötigt keine weiteren Parameter und liefert ein Objekt in folgender Form zurück:
 
 
 
  Type  : JSON
 
  Token :
 
  Data  : @{version=8.1.2.9268; machineName=DEMO}
 
 
 
Die ''Type'' Eigenschaft des Objekts entspricht dabei entweder dem ''-Code'' Parameter des API-Client-Objekt ("JSON" oder "XML"), oder enthält für asynchron ausgeführte API-Befehle den Wert "JOB" (s.u.) und charakterisiert den Typ des in der ''Data'' Eigenschaft enthaltenen Objekts. Die ''Token'' Eigenschaft ist ebenfalls nur für asynchron ausgeführte API-Befehle relevant.
 
 
 
In der ''Data'' Eigenschaft befindet sich das vom MailStore Server zurückgelieferte Ergebnis, hier als JSON Objekt:
 
 
 
  PS C:\MailStore Scripting Tutorial\PowerShell\Scripts>$return.Data|fl
 
  version    : 8.1.2.9268
 
  machineName : DEMO
 
 
 
== API Wrapper Funktionen mit Parametern aufrufen ==
 
 
 
Viele MailStore Server Administration API Befehle erfordern die Angabe von Parametern. Selbstverständlich ist der MailStore PowerShell API Wrapper in der Lage, diese mittels ''Invoke-MSSApiCall'' zu übermitteln. Zur Erläuterung soll das folgende Skript dienen, das im Beispielskriptpaket als ''Example2.ps1'' enthalten ist.
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Import-Module 'C:\MailStore Scripting Tutorial\PowerShell\API-Wrapper\MSS.PS.Lib.psd1'
 
  $mssapiclient = New-MSSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -Code JSON -IgnoreInvalidSSLCerts
 
  $users = (Invoke-MSSApiCall $mssapiclient "GetUserList").Data
 
  foreach ($user in $users) {(Invoke-MSSApiCall $mssapiclient "GetUserInfo" @{userName = $user.userName}).Data | fl}
 
</source>
 
 
 
Das Skript liefert Details über die in MailStore Server angelegten Benutzer zurück und gibt sie als Liste aus. Es macht sich dabei zunutze, dass der MailStore PowerShell API Wrapper die Antworten der MailStore Server Management API direkt in Objekte konvertiert, deren Eigenschaften dann direkt weiterverwendet werden können.
 
 
 
Der im Skript aufgerufene API Befehl ''[[MailStore_Server_Administration_API_Commands#GetUserInfo|GetUserInfo]]'' erfordert einen Parameter ''userName''. Die Funktion ''Invoke-MSSApiCall'' erwartet Parameter als Hashtable, also z.B. in der Form ''@{Parametername1 = Wert1; Parametername2 = Wert2;...}''. Die Parameternamen sind dabei case sensitive.
 
 
 
Zunächst wird die Liste der MailStore Server Benutzer mittels des API Befehls ''[[MailStore_Server_Administration_API_Commands#GetUserList|GetUserList]]'' abgerufen. Dieser liefert ein Array mit Einträgen folgenden Aufbaus zurück:
 
 
 
  userName          : abby.hernandez
 
  fullName          : Abby Hernandez
 
  distinguishedName : CN=Abby Hernandez,OU=tutorial,DC=example,DC=com
 
 
 
Über diese Einträge wird nun iteriert und dabei die ''userName'' Eigenschaft jedes Eintrags als Parameter des API Befehls ''[[MailStore_Server_Administration_API_Commands#GetUserInfo|GetUserInfo]]'' verwendet. Das Ergebnis für den o.g. Eintrag sieht wie folgt aus:
 
 
 
  userName            : abby.hernandez
 
  fullName            : Abby Hernandez
 
  distinguishedName  : CN=Abby Hernandez,OU=tutorial,DC=example,DC=com
 
  authentication      : directoryServices
 
  emailAddresses      : {[email protected]}
 
  pop3UserNames      : {}
 
  privileges          : {login}
 
  privilegesOnFolders : {@{folder=abby.hernandez; privileges=System.Object[]}}
 
 
 
An der ''privilegesOnFolders'' Eigenschaft ist gut erkennbar, dass die zurückgegebenen Objekte durchaus tiefer verschachtelt sein und ihrerseits weitere Objekte enthalten können.
 
 
 
= API Wrapper Funktionen für asynchron ausgeführte API Befehle aufrufen =
 
 
 
MailStore Server Administration API-Befehle, deren Ausführung typischerweise länger dauert, werden vom Server asynchron ausgeführt. Der MailStore PowerShell API Wrapper erkennt den Aufruf dieser [[MailStore_Server_Administration_API#Asynchron_ausgef.C3.BChrte_Befehle|asynchron ausgeführten API Befehle]] und führt diese als [http://technet.microsoft.com/en-us/library/hh847783%28v=wps.620%29.aspx PowerShell Job] im Hintergrund aus. Das Skript ''Example3.ps1'' aus dem Beispielskriptpaket verdeutlicht diese Funktionalität:
 
 
 
<source lang="powershell" smart-tabs="true" toolbar="false" gutter="false">
 
  Import-Module 'C:\MailStore Scripting Tutorial\PowerShell\API-Wrapper\MSS.PS.Lib.psd1'
 
  $mssapiclient = New-MSSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -Code JSON -IgnoreInvalidSSLCerts
 
  $return = invoke-MSSApiCall $mssapiclient "VerifyStore" @{id = "1"}
 
  if ($return.Type -eq "JOB") {
 
      Wait-Job $return.Data
 
      Receive-Job $return.Data
 
  } else {
 
      $return.Data
 
  }
 
</source>
 
 
 
Der im Skript aufgerufene API Befehl ''[[MailStore_Server_Administration_API_Commands#VerifyStore|VerifyStore]]'' liefert ein Objekt mit der ''Type'' Eigenschaft "JOB" zurück.
 
 
 
  Type  : JOB
 
  Token : sa9e8d780329f1e0c59503a2e041f7c72b
 
  Data  : System.Management.Automation.PSRemotingJob
 
 
 
Im Unterschied zu den Rückgabeobjekten bei synchron ausgeführten API Befehlen ist hier die ''Token'' Eigenschaft gesetzt, sie enthält eine vom Server zurückgegebene, eindeutige ID des Serverprozesses. Die ''Data'' Eigenschaft enthält den PowerShell Job, der im Hintergrund die vom Server zurückgelieferten Statusobjekte verarbeitet.
 
 
 
== API Wrapper PowerShell Jobs ==
 
 
 
Der in der ''Data'' Eigenschaft enthaltene PowerShell Job fragt den Status des zugehörigen Serverprozesses in regelmäßigen Intervallen ab (standardmäßig alle 500 ms) und wird beendet, wenn dieser abgeschlossen ist. Mittels des PowerShell cmdlets [http://technet.microsoft.com/en-us/library/hh849735.aspx Wait-Job] kann ein Skript auf die Fertigstellung des Jobs warten, anschließend kann das Ergebnis des Jobs mittels [http://technet.microsoft.com/en-us/library/hh849718.aspx Receive-Job] abgerufen werden:
 
 
 
  Type      : JSON
 
  Token      :
 
  Data      : @{status=succeeded; progressPercentage=100; messages=System.Collections.ArrayList}
 
  RunspaceId : 2eca1237-4504-4b63-a153-d326adf8c744</pre>
 
 
 
<p class=msnote>'''Hinweis:''' Die ''RunspaceId'' wird von der PowerShell automatisch erzeugt und kann hier ignoriert werden.</p>
 

Aktuelle Version vom 18. September 2014, 13:21 Uhr


Important notice: The PowerShell API wrapper for the MailStore Server Administration API provided on this website is to be regarded as an example implementation of an API client. This wrapper should help system administrators and developers to quickly understand how MailStore Server Administration API calls work and how to use them in their own scripts.
Please understand that beyond this documentation no further support for the Powershell API wrapper is provided. Unless stated otherwise, the PowerShell API wrapper as well as all related example scripts are released under the terms and conditions of the MIT License.


This tutorial aims to explain the usage of the Administration API through simple Windows PowerShell example scripts. Basic knowledge of MailStore Server, Windows and PowerShell is a necessary precondition. In order to prevent loss of data, service interruption or other problems, it is highly recommended to use a non-productive test environment for this tutorial as well as for script development in general. The 30-day-trial version of MailStore Server is perfectly suited for this.

Installation of Necessary Components

The examples demonstrated here use the MailStore PowerShell API Wrapper and are compatible with Windows PowerShell 3.0 and higher. Depending on your version of Windows it might be necessary to download and install a compatible version of PowerShell first. You can find the components necessary for this tutorial here:

Please take note of the system requirements and further notices for the respective version of the Windows Management Framework.

Important Notice: Installation of a Windows Management Framework on systems that require a specific version of Windows PowerShell, such as Microsoft Exchange Servers, is not supported and may lead to massive system failures and data loss.

After downloading and installing Windows PowerShell (if necessary) please unzip the MailStore PowerShell API Wrapper and the example scripts (to C:\MailStore Server Scripting Tutorial\PowerShell\ by default).

Neither the MailStore PowerShell API Wrapper nor the example scripts are digitally signed, therefore execution of such scripts has to be enabled in an administrative PowerShell session using

  Set-ExecutionPolicy -ExecutionPolicy Unrestricted

Importing the MailStore PowerShell API Wrapper

The MailStore PowerShell API Wrapper is implemented as a PowerShell Script Module (MS.PS.Lib.psm1) and can thus be imported in a PowerShell session via its manifest (MS.PS.Lib.psd1) by using Import-Module.

Please open a PowerShell session and import the API wrapper module using this command:

  Import-Module "C:\MailStore Server Scripting Tutorial\PowerShell\API-Wrapper\MS.PS.Lib.psd1"

Getting Information about the MailStore PowerShell API Wrapper

The MailStore PowerShell API Wrapper provides several functions and variables to access the MailStore Server Administration API, following PowerShell conventions. Enter the following command to get information about these features:

  Get-Module MS.PS.Lib | fl

More detailed information is available through the module's properties. For example,

  (Get-Module MS.PS.Lib).ExportedFunctions

returns the functions provided by the module. Via

  Get-Help *MSApi*

the MailStore PowerShell API Wrapper returns inline help for all its functions.

Calling API Wrapper Functions

The following example script (Example1.ps1 in the tutorial package) explains the basic usage of MailStore PowerShell API Wrapper functions.

  Import-Module '..\API-Wrapper\MS.PS.Lib.psd1'
  $msapiclient = New-MSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -IgnoreInvalidSSLCerts
  $return = Invoke-MSApiCall $msapiclient "GetServerInfo"
  $return | fl

The function New-MSApiClient creates a new API client object, which is used by the Invoke-MSApiCall function for API calls. The values for -Username, -Password, -MailStoreServer and -Port used in the script are the function's defaults, only the switch -IgnoreInvalidSSLCerts has to be set if untrusted certificates are used; otherwise an error occurs.

Apart from the API client object, Invoke-MSApiCall needs an API command and its parameters if applicable. The command GetServerInfo in the script does not have any parameters and returns a JSON object as follows:

 PS C:\MailStore Server Scripting Tutorial\PowerShell\Scripts>$return | fl
 error           : 
 token           : 
 statusVersion   : 2
 statusCode      : succeeded
 percentProgress : 
 statusText      : 
 result          : @{version=9.1.0.10258; machineName=PC001}
 logOutput       : 

If the call has succeeded, the status object's result property contains another JSON object with the data returned by the function:

 PS C:\MailStore Server Scripting Tutorial\PowerShell\Scripts>$return.result | fl
 version     : 9.1.0.10258
 machineName : PC001

Providing Parameters

For most MailStore Server Administration API commands you need to provide parameters. Of course, the MailStore PowerShell API Wrapper's Invoke-MSApiCall function can submit these parameters, as demonstrated by the following script (Example2.ps1 in the tutorial package):

  Import-Module '..\API-Wrapper\MS.PS.Lib.psd1'
  $msapiclient = New-MSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -IgnoreInvalidSSLCerts
  $users = (Invoke-MSApiCall $msapiclient "GetUsers").result
  foreach ($user in $users) {(Invoke-MSApiCall $msapiclient "GetUserInfo" @{userName = $user.userName}).result | fl}

The scripts lists details about the users created in MailStore Server. Because the MailStore PowerShell API Wrapper converts MailStore Server Management API responses into objects, their properties can be used directly in the script's workflow.

The API command GetUserInfo used in the script requires a parameter userName. The function Invoke-MSApiCall expects parameters as a hashtable, e.g. @{parametername1 = value1; parametername2 = value2;...}. Parameter names are case sensitive.

First, MailStore Server's user list is requested with the API command GetUsers which returns an array of user entries as follows:

 userName          : abby.hernandez
 fullName          : Abby Hernandez
 distinguishedName : CN=Abby Hernandez,OU=tutorial,DC=example,DC=com

The script now iterates over this array using the userName property of each entry as a parameter for the API command GetUserInfo. For the entry listed above the result could be as follows:

 userName            : abby.hernandez
 fullName            : Abby Hernandez
 distinguishedName   : CN=Abby Hernandez,OU=tutorial,DC=example,DC=com
 authentication      : directoryServices
 emailAddresses      : {[email protected]}
 pop3UserNames       : {}
 privileges          : {login}
 privilegesOnFolders : {@{folder=abby.hernandez; privileges=System.Object[]}}

As can be seen in the privilegesOnFolders property, returned objects may be nested and may also contain further objects.

Handling Asynchronous API Calls

The server may decide to execute Administration API commands asynchronously if their execution takes more time. The MailStore PowerShell API Wrapper can either wait for such asynchronously executed API commands to complete or run them as PowerShell Jobs in the background.

Waiting for Asynchronous API Calls to Complete

A script's execution can be interrupted until a PowerShell Job created by the API wrapper terminates as demonstrated by the following script (Example3.ps1 in the tutorial package):

  Import-Module '..\API-Wrapper\MS.PS.Lib.psd1'
  $msapiclient = New-MSApiClient -Username "admin" -Password "admin" -Server "localhost" -Port 8463 -IgnoreInvalidSSLCerts
  $return = Invoke-MSApiCall $msapiclient "VerifyStore" @{id = "1"}
  $return | fl

By using Invoke-MSApiCall the API wrapper waits for an API command that is executed asynchronously by MailStore Server to complete and simply returns its final result.

Subscribing to Events Triggered by Asynchronous API Calls

Instead of interrupting a script's execution, the PowerShell Jobs created by the API wrapper can be reacted to while they are running in the background. These jobs trigger a PowerShell EngineEvent with each status request that the script can subscribe to in order to execute further code on each occurrence. To demonstrate this, the previous script needs to be adapted only a bit (Example4.ps1 in the tutorial package):

  Import-Module '..\API-Wrapper\MS.PS.Lib.psd1'
  $msapiclient = New-MSApiClient -Username "admin" -Password "admin" -Server "localhost" -Port 8463 -IgnoreInvalidSSLCerts
  $return = Start-MSApiCall $msapiclient "VerifyStore" @{id = "1"}
  if ($return.statusCode -eq "running") {
      $mssevent = Register-EngineEvent -SourceIdentifier $return.Token -Action {write-host $event.MessageData}
  } else {
      $return | fl
  }

By using Start-MSApiCall the API wrapper runs an API command that is executed asynchronously by MailStore Server in the background and returns its first result. The script subscribes to the event that is triggered by the background job via Register-EngineEvent, using the return object's Token property as SourceIdentifier. By that property the event relates to the triggering PowerShell Job and thus to the server process. The Action script block is itself created as a PowerShell Job that is executed with each triggering of the event. Through the MessageData property of the $event automatic variable the script block can access the return object provided by the background job. That object contains the status of the server process:

 @{error=; token=e2b7c58ff37df64e2b62bb02bde9bbfd; statusVersion=77; statusCode=running; percentProgress=95; statusText=; result=; logOutput=  1400 messages verified...}

Via these mechanisms the script can execute further tasks while monitoring the server process in the background. Execution and handling of multiple asynchronous API commands is also possible this way.

Cancelling Asynchronous API Calls

To cancel the execution of an asynchronous API command, use Stop-MSApiCall with either the token or the return object. For the example above the call would be:

  Stop-MSApiCall $MSApiclient -AsyncReturnObject $return

Pinning the TLS version

The API Wrapper supports TLS1.2, TLS1.1 and TLS1.0 connections and uses the highest version available. In case only a specific TLS version should be used, the SecurityProtocol parameter can be used. The supported values are Tls12, Tls11 and Tls.

  Import-Module '..\API-Wrapper\MS.PS.Lib.psd1'
  $msapiclient = New-MSApiClient -Username admin -Password admin -MailStoreServer localhost -Port 8463 -IgnoreInvalidSSLCerts -SecurityProtocol Tls12