PowerShell API-Wrapper Tutorial: Unterschied zwischen den Versionen

[unmarkierte Version][gesichtete Version]
 
(33 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt)
Zeile 1: Zeile 1:
++ Under construction ++
+
{{raw::en:PowerShell API Wrapper Tutorial}}
  
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]]
<p class=msnote>'''Hinweis:''' Es wird empfohlen, für dieses Tutorial und grundsätzlich für die Skriptentwicklung eine eigene, nicht produktive Instanz 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]]<br/>
 
[[Media:MailStorePSTutorialScripts.zip?|MailStore PowerShell Tutorial Beispielskripte]]<br/>
 
[https://my.mailstore.com/TrialLicense/RequestForm?lang=de 30-Tage-Testversion von MailStore Server]<br/>
 
[http://www.microsoft.com/en-us/download/details.aspx?id=34595 Windows Management Framework 3.0] (enthält die PowerShell 3.0)<br/>
 
[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 style="color:red">'''Wichtiger Hinweis:'''</span> 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.</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\'').
 
 
 
= 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:
 
<pre>Import-Module "C:\MailStore Scripting Tutorial\PowerShell\API-Wrapper\MSS.PS.Lib.psd1"</pre>
 
 
 
<div style="border:1px solid gray; padding:6px 10px 6px 10px; margin:0px 0px 12px 0px">'''Hinweis:''' 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
 
<pre>Set-ExecutionPolicy -ExecutionPolicy Unrestricted</pre>
 
zugelassen werden.</div>
 
 
 
== 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:
 
<pre>Get-Module MSS.PS.Lib|fl</pre>
 
Mittels der Eigenschaften des Moduls kann man noch detailliertere Informationen abrufen. Beispielsweise gibt
 
<pre>(Get-Module MSS.PS.Lib).ExportedVariables</pre>
 
die zur Verfügung gestellten Variablen des Moduls zurück.<br/>
 
Mittels
 
<pre>Get-Help</pre>
 
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''.
 
<pre>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</pre>
 
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.<br/>
 
''Invoke-MSSApiCall'' benötigt neben dem API-Client-Objekt einen [[MailStore_Server_Administration_API_Commands|API Befehl]] und ggf. dessen Parameter. Der Befehl ''GetServerInfo'' im Skript benötigt keine weiteren Parameter und liefert ein Objekt in folgender Form zurück:
 
 
 
<pre>Type  : JSON
 
Token :
 
Data  : @{version=8.1.2.9268; machineName=DEMO}</pre>
 
 
 
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.<br/>
 
In der ''Data'' Eigenschaft befindet sich das vom MailStore Server zurückgelieferte Ergebnis, hier als JSON Objekt:
 
 
 
<pre>PS C:\MailStore Scripting Tutorial\PowerShell\Scripts>$return.Data|fl
 
version    : 8.1.2.9268
 
machineName : DEMO</pre>
 
 
 
== 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 Beispielskript dienen, das im Beispielskriptpaket als ''Example2.ps1'' enthalten ist.
 
<pre>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"
 
foreach ($user in $users.Data) {(Invoke-MSSApiCall $mssapiclient "GetUserInfo" @{userName = $user.userName}).Data|fl}</pre>
 

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