8
0

The complete folder structure has been changed or updated

This commit is contained in:
2025-09-19 18:24:40 +02:00
parent 796473a8c9
commit 1f0d1613a5
212 changed files with 330924 additions and 762 deletions

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,735 @@
<#------------------------------------------------------------------------
PowerShell Scripting Library
for MailStore Server and MailStore Service Provider Edition
Requires Microsoft PowerShell 3.0 or higher
Copyright (c) 2014 - 2019 MailStore Software GmbH
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------#>
if ($PSVersionTable.PSVersion.Major -lt 3) {
throw New-Object System.NotSupportedException "PowerShell V3 or higher required."
}
[System.Net.SecurityProtocolType]$DefaultSecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls11 -bor [System.Net.SecurityProtocolType]::Tls
<#
.SYNOPSIS
Scriptblock called by "InternalMSApiCall" to handle long running API processes.
.DESCRIPTION
Scriptblock called by "InternalMSApiCall" to handle long running API processes.
Optionally fires events to notify the parent session of Status changes.
Returns the final HTTP response as JSON object.
.PARAMETER MSApiClient
MS API client object created by "New-MSApiClient".
.PARAMETER StatusObject
Initial HTTP answer returned by the API as JSON object.
.PARAMETER StatusTimeout
Time in milliseconds until the the server stops waiting for a new Status updates to send.
.PARAMETER UseStatusEvents
If set to true, an event is fired for each status change.
.FUNCTIONALITY
start-job -ArgumentList <MS API client>, <Initial HTTP response object>, <Timeout>, <UseStatusEvents> -ScriptBlock $sbPullStatus
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#Long_Running_Processes
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#Long_Running_Processes
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#Initial_HTTP_Response
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#Initial_HTTP_Response
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#HTTP_Response_to_Periodic_Progress_Requests
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#HTTP_Response_to_Periodic_Progress_Requests
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#Final_HTTP_Response
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#Final_HTTP_Response
.OUTPUTS
<PSCustomObject>
JSON object that contains the final HTTP response.
<PSEngineEvent>
A custom PowerShell Engine Event that is fired in case of a Status version change. with the following properties:
-SourceIdentifier <string>
The initial Status token.
-MessageData <PSCustomObject>
JSON object with the current Status returned by the server.
#>
$sbPullStatus = [scriptblock]::Create({
Param(
[Parameter(Mandatory = $True, Position = 1)]
[ValidateNotNull()]
[PSCustomObject]$MSApiClient,
[Parameter(Mandatory = $True, Position = 2)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$StatusObject,
[Parameter(Position = 3)]
[ValidateNotNull()]
[int]$StatusTimeout = 5000,
[Parameter(Position = 4)]
[bool]$UseStatusEvents = $True
)
[System.Uri]$StatusUri = New-Object System.Uri ("HTTPS://{0}:{1}/{2}{3}" -f $MSApiClient.Server, $MSApiClient.Port.ToString(), "api/", "get-status")
if ($UseStatusEvents) {
# The Status token returned by the initial API request identifies the server process. We use it to as event source so the parent PS session knows to which API call the Status relates.
Register-EngineEvent -SourceIdentifier ($StatusObject.token) -Forward
}
# We need to set ServerCertificateValidationCallback and SecurityProtocol again as this is most likely a new PS session inside a job
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $MSApiClient.IgnoreInvalidSSLCerts }
[System.Net.ServicePointManager]::SecurityProtocol = $MSApiClient.SecurityProtocol
[Microsoft.PowerShell.Commands.WebRequestSession]$Session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$session.Credentials = $MSApiClient.Credentials
do {
$StatusCode = ""
# We provide the status' token, last known version and a timeout value. The server will wait for that time at most for a new status, therefore it is not necessary for our client process to wait itself.
$Post = @{token = $StatusObject.token; lastKnownStatusVersion = $StatusObject.statusVersion; millisecondsTimeout = $StatusTimeout}
try {
[Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject]$Response = Invoke-WebRequest -Uri $StatusUri.AbsoluteUri -Method Post -Body $Post -WebSession $Session -UseBasicParsing -MaximumRedirection 0 -ErrorAction SilentlyContinue
}
catch {
$Response = $global:Error[0].Exception.Response
if ($Response -eq $null) {
throw $global:Error[0].Exception
}
}
switch([System.Net.HttpStatusCode]$Response.StatusCode) {
([System.Net.HttpStatusCode]::OK) {
if ($Response.Content -eq $null) {
$StatusObject = $null
$StatusCode = ""
} else {
# The PS commandlets do not respect the response's encoding, putting the BOM from the server's response into the content field >:-[
# We need to remove the BOM so that ConvertFrom-Json succeeds.
$null = $Response.RawContentStream.Seek(0, [System.IO.SeekOrigin]::Begin) # Reset the stream
$StatusObject = (New-Object System.IO.StreamReader $Response.RawContentStream, $Response.BaseResponse.CharacterSet).ReadToEnd() | ConvertFrom-Json
$StatusCode = $StatusObject.StatusCode
# Fire a new PS Engine Event with the status token as SourceIdentifier.
# The calling session knows the token and can thus identify to which API call the event relates, especially if there are multiple jobs in the queue.
# MessageData contains a return object that has the current status as JSON object in its Data property.
if ($UseStatusEvents) {
$null = New-Event -SourceIdentifier $StatusObject.token -MessageData $StatusObject
}
}
}
([System.Net.HttpStatusCode]::Unauthorized) {
throw New-Object System.Net.WebException "Authentication failed. Check username and password."
}
([System.Net.HttpStatusCode]::NotFound) {
throw New-Object System.Net.WebException "Session expired or wrong token."
}
default {
throw New-Object System.Net.WebException ("({0}) {1}: {2}" -f [int]$Response.StatusCode, $Response.StatusDescription , $global:Error[0])
}
}
} while ($StatusCode -eq "running")
return $StatusObject
})
<#
Sends an API call to the MailStore or SPE Management Server.
.DESCRIPTION
Sends an API call to the MailStore or SPE Management Server.
Optionally runs a call asynchronously through background jobs.
Returns a JSON <PSCustomObject>.
.PARAMETER MSApiClient
MS API client object created by "New-MSApiClient".
.PARAMETER ApiFunction
A valid MS API function.
.PARAMETER ApiFunctionParameters
The parameters for the API function.
Provide as a hashtable, e.g. @{parameter1 = value1; parameter2 = value2; ...},
or PSCustomObject with parameters mapped to properties.
.PARAMETER StatusTimeout
Time in milliseconds until the the server stops waiting for a new status update to send.
.PARAMETER RunAsynchronously
If provided, an API function that the server decides to run asynchronously is run as a background job.
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API_Commands
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Function_Reference
.OUTPUTS
A JSON <PSCustomObject> that encapsulates the HTTP response of the MS server.
#>
function InternalMSApiCall {
Param(
[Parameter(Mandatory = $True, Position = 1)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$MSApiClient,
[Parameter(Mandatory = $True, Position = 2)]
[ValidateScript({$MSApiClient.SupportedApiFunctions.name.Contains($_)})]
[string]$ApiFunction,
[Parameter(Position = 3)]
[System.Object]$ApiFunctionParameters = @{},
[Parameter(Position = 4)]
[ValidateNotNull()]
[int]$StatusTimeout = 5000,
[Parameter(Position = 5)]
[switch]$RunAsynchronously
)
# If $ApiFunctionParameters is passed as null, use an empty hashtable
if (!$ApiFunctionParameters) {
[Hashtable]$ApiFunctionParametersHT = @{}
} else {
# If necessary, convert PSCustomObject to Hashtable for further processing
switch ($ApiFunctionParameters.GetType().Name) {
"Hashtable" {
[Hashtable]$ApiFunctionParametersHT = $ApiFunctionParameters
}
"PSCustomObject" {
[Hashtable]$ApiFunctionParametersHT = @{}
$ApiFunctionParameters.psobject.properties | Foreach { $ApiFunctionParametersHT[$_.Name] = $_.Value }
}
default {
throw New-Object System.ArgumentException ('API function parameters must be passed either as Hashtable or as PSCustomObject.')
}
}
}
# Get the parameters for the API function supplied. The function itself has been checked in the Param block.
$MSApiFunctionWithParameters = $MSApiClient.SupportedApiFunctions | Where-Object {$_.name -eq $ApiFunction}
# Check whether the API function requires any parameters at all
if ($MSApiFunctionWithParameters.args.name) {
[Array]$ParameterNames = $MSApiFunctionWithParameters.args.name
} else {
[Array]$ParameterNames = @()
}
# Check whether parameters have been supplied that the API function does not support
[Array]$IllegalParams = Compare-Object -ReferenceObject $ParameterNames -DifferenceObject ([Array]$ApiFunctionParametersHT.Keys) -PassThru | Where-Object {$_.SideIndicator -EQ "=>"}
if ($IllegalParams.Count -gt 0) {
throw New-Object System.ArgumentException ('Illegal Arguments: {0}' -f ($IllegalParams -join ", "))
} else {
# Parameters which have their NULLABLE property set to false are mandatory
$MSApiFunctionMandatoryParameters = [Array]($MSApiFunctionWithParameters.args | Where-Object {$_.nullable -EQ $false})
# Check whether any parameters are mandatory at all
if ($MSApiFunctionMandatoryParameters.name) {
[Array]$ParameterNames = $MSApiFunctionMandatoryParameters.name
} else {
[Array]$ParameterNames = @()
}
# Check whether mandatory parameters are missing
[Array]$MissingParams = Compare-Object -ReferenceObject $ParameterNames -DifferenceObject ([Array]$ApiFunctionParametersHT.Keys) -PassThru | Where-Object {$_.SideIndicator -EQ "<="}
if ($MissingParams.Count -gt 0) {
throw New-Object System.ArgumentException ('Missing Arguments: {0}' -f ($MissingParams -join ", "))
} else {
#Place Argument Type Check Here. We let the server sort out most of it ;-)
#Except for Booleans where the server supports only lower case values in compliance with JSON specs
[Array]$BoolParams = $MSApiFunctionWithParameters.args | Where-Object {$_.type.ToLowerInvariant() -eq "bool"}
if ($BoolParams.Count -gt 0) {
[Array]$SuppliedBoolParams = Compare-Object -ReferenceObject $BoolParams.Name -DifferenceObject ([Array]$ApiFunctionParametersHT.Keys) -IncludeEqual -ExcludeDifferent -PassThru
foreach ($SuppliedBoolParam in $SuppliedBoolParams) {
$ApiFunctionParametersHT[$SuppliedBoolParam] = $ApiFunctionParametersHT[$SuppliedBoolParam].ToString().ToLowerInvariant()
}
}
#JSON parameters need to be converted to string if they are supplied as any other type
[Array]$JSONParams = $MSApiFunctionWithParameters.args | Where-Object {$_.type.ToLowerInvariant() -eq "json"}
if ($JSONParams.Count -gt 0) {
[Array]$SuppliedJSONParams = Compare-Object -ReferenceObject $JSONParams.Name -DifferenceObject ([Array]$ApiFunctionParametersHT.Keys) -IncludeEqual -ExcludeDifferent -PassThru
foreach ($SuppliedJSONParam in $SuppliedJSONParams) {
if ($ApiFunctionParametersHT[$SuppliedJSONParam].GetType().Name.ToLowerInvariant() -ne "string") {
$ApiFunctionParametersHT[$SuppliedJSONParam] = $ApiFunctionParametersHT[$SuppliedJSONParam] | ConvertTo-Json -Depth 10
}
}
}
}
}
# If a URI path is defined for the API function, use it, otherwise use the default path
$functionPath = if ($MSApiFunctionWithParameters | Get-Member "path") { $MSApiFunctionWithParameters.path } else { "api/invoke/" }
[System.Uri]$Uri = New-Object System.Uri ("HTTPS://{0}:{1}/{2}{3}" -f $MSApiClient.Server, $MSApiClient.Port.ToString(), $functionPath, $ApiFunction)
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $MSApiClient.IgnoreInvalidSSLCerts }
[System.Net.ServicePointManager]::SecurityProtocol = $MSApiClient.SecurityProtocol
[Microsoft.PowerShell.Commands.WebRequestSession]$Session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$Session.Credentials = $MSApiClient.Credentials
# MS includes a BOM in most of its answers (especially the serialized JSON) which the PS commandlets cannot handle.
# Therefore we have to use Invoke-WebRequest instead of Invoke-RestMethod and do the parsing ourselves.
# Redirection and non terminating exceptions are suppressed.
try {
[Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject]$Response = Invoke-WebRequest -Uri $Uri.AbsoluteUri -Method Post -Body $ApiFunctionParametersHT -WebSession $Session -UseBasicParsing -MaximumRedirection 0 -ErrorAction SilentlyContinue
}
catch {
$Response = $global:Error[0].Exception.Response
if ($Response -eq $null) {
throw $global:Error[0].Exception
}
}
# If the web request itself has been successful, we get a StatusCode.
switch([System.Net.HttpStatusCode]$Response.StatusCode) {
([System.Net.HttpStatusCode]::OK) {
# Respect the response's encoding and thus get rid of the BOM if necessary (see above) so that ConvertFrom-Json succeeds.
$null = $Response.RawContentStream.Seek(0, [System.IO.SeekOrigin]::Begin) # Reset the stream
$ResponseObject = (New-Object System.IO.StreamReader $Response.RawContentStream, $Response.BaseResponse.CharacterSet).ReadToEnd() | ConvertFrom-Json
if ($ResponseObject.StatusCode -eq "running") {
if ($RunAsynchronously.IsPresent) {
# For a long running server process, create a background job encapsuled in $sbPullStatus that does the Status handling.
$null = Start-Job -ArgumentList $MSApiClient, $ResponseObject, $StatusTimeout, $True -ScriptBlock $sbPullStatus
} else {
$ResponseObject = Invoke-Command -ArgumentList $MSApiClient, $ResponseObject, $StatusTimeout, $False -ScriptBlock $sbPullStatus -NoNewScope
}
}
# Return the JSON response object.
return $ResponseObject
}
([System.Net.HttpStatusCode]::Unauthorized) {
throw New-Object System.Net.WebException "Authentication failed. Check username and password."
}
default {
throw New-Object System.Net.WebException ("({0}) {1}: {2}" -f [int]$Response.StatusCode, $Response.StatusDescription , $global:Error[0])
}
}
}
<#
.SYNOPSIS
Creates a new MS API client object.
.DESCRIPTION
Creates a new MS API client object.
Returns an MS API client object.
.PARAMETER Username
Username of a MailStore Server or SPE administrator.
.PARAMETER Password
Password of that MailStore Server or SPE administrator.
.PARAMETER Credentials
Credentials of a MailStore Server or SPE administrator.
Alternative to providing <Username> and <Password>.
.PARAMETER MailStoreServer
DNS name or IP address of the MailStore Server.
.PARAMETER ManagementServer
DNS name or IP address of the SPE Management Server.
.PARAMETER Port
Port that the MailStore or SPE Management Server listens to for API calls.
.PARAMETER IgnoreInvalidSSLCerts
If included, errors due to invalid SSL certificates are ignored.
If omitted, only certificates that can be validated can be used.
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API_Commands
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Function_Reference
.OUTPUTS
<PSCustomObject>
Object that encapsulates an MS API client instance with the following properties:
-Server <string>
Same as MailStoreServer or ManagementServer parameter, see above.
-Port <string>
Same as input parameter, see above.
-IgnoreInvalidSSLCerts <bool>
Same as input parameter, see above.
-SupportedApiFunctions <PSCustomObject>
A JSON object that contains all functions the MS Management Server supports.
Data fields are:
-Name <string[]>
Name of the API function.
-Args <string[]>
List of arguments that the API function expects.
-Path [<string[]>]
The URI path that a request should use for this function.
If empty the default path "/invoke/<function>" is used.
Please refer to http://en.help.mailstore.com/MailStore_Server_Administration_API_Commands
or http://en.help.mailstore.com/spe/Management_API_-_Function_Reference for futher details.
#>
function New-MSApiClient {
[CmdletBinding(DefaultParameterSetName="MSSCredentialsAsStringsParameterSet")]
Param(
[Parameter(ParameterSetName = "MSSCredentialsAsStringsParameterSet", Position = 1, Mandatory = $true)]
[Parameter(ParameterSetName = "SPECredentialsAsStringsParameterSet", Position = 1, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Username = "admin",
[Parameter(ParameterSetName = "MSSCredentialsAsPSCredentialObjectParameterSet", Position = 1, Mandatory = $true)]
[Parameter(ParameterSetName = "SPECredentialsAsPSCredentialObjectParameterSet", Position = 1, Mandatory = $true)]
[ValidateNotNull()]
[pscredential]$Credentials,
[Parameter(ParameterSetName = "MSSCredentialsAsStringsParameterSet", Position = 2, Mandatory = $true)]
[Parameter(ParameterSetName = "SPECredentialsAsStringsParameterSet", Position = 2, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$Password,
[Parameter(ParameterSetName = "MSSCredentialsAsStringsParameterSet", Position = 3, Mandatory = $true)]
[Parameter(ParameterSetName = "MSSCredentialsAsPSCredentialObjectParameterSet", Position = 2, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Alias("Server")]
[string]$MailStoreServer = "localhost",
[Parameter(ParameterSetName = "SPECredentialsAsStringsParameterSet", Position = 3, Mandatory = $true)]
[Parameter(ParameterSetName = "SPECredentialsAsPSCredentialObjectParameterSet", Position = 2, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$ManagementServer = "localhost",
[Parameter(ParameterSetName = "MSSCredentialsAsStringsParameterSet", Position = 4)]
[Parameter(ParameterSetName = "SPECredentialsAsStringsParameterSet", Position = 4)]
[Parameter(ParameterSetName = "MSSCredentialsAsPSCredentialObjectParameterSet", Position = 3)]
[Parameter(ParameterSetName = "SPECredentialsAsPSCredentialObjectParameterSet", Position = 3)]
[ValidateRange(1024,65535)]
[int]$Port,
[Net.SecurityProtocolType]$SecurityProtocol = $DefaultSecurityProtocol,
[switch]$IgnoreInvalidSSLCerts
)
# If username and password have been provided, store them in a PSCredential object.
if ($PSBoundParameters.ContainsKey("Password")) {
$Credentials = New-Object System.Management.Automation.PSCredential($Username,(ConvertTo-SecureString $Password -AsPlainText -Force))
}
# Get the server name based on the parameter set used.
switch -wildcard ($PSCmdlet.ParameterSetName) {
"MSS*" {
$Server = $MailStoreServer
}
"SPE*" {
$Server = $ManagementServer
}
}
# If no port has been provided, make a best guess based on the server parameter name.
if (!($PSBoundParameters.ContainsKey("Port"))) {
switch -wildcard ($PSCmdlet.ParameterSetName) {
"MSS*" {
$Port = 8463
}
"SPE*" {
$Port = 8474
}
}
}
# We provide a basic set of supported API functions to be able to login and initialize the MS API client object. The full set of functions will be retrieved later through "get-metadata" (see below).
$API_SUPPORTEDFUNCTIONS = '[{"name": "get-status","args": [{"name": "token","type": "string","nullable": false},{"name": "lastKnownStatusVersion","type": "number","nullable": false},{"name": "millisecondsTimeout","type": "number","nullable": false}],"path": "api/"},{"name": "get-metadata","args": [],"path": "api/"},{"name": "cancel-async","args": [{"name": "token","type": "string","nullable": false}],"path": "api/"}]'
[PSCustomObject]$MSApiClient = @{Credentials = $Credentials; Server = $Server; Port = $Port; SecurityProtocol = $SecurityProtocol; IgnoreInvalidSSLCerts = $IgnoreInvalidSSLCerts.IsPresent; SupportedApiFunctions = $API_SUPPORTEDFUNCTIONS | ConvertFrom-Json}
# Retrieve a list of all API functions that this installation of MS supports and convert it into a JSON object. Use a parsing depth of 10 levels just be sure and the default of 2 (!) is a bit ... insufficient.
$SupportedApiFunctions = InternalMSApiCall -MSApiClient $MSApiClient -ApiFunction "get-metadata" | ConvertTo-Json -Depth 10
# Join our basic set with the retrieved set because "get-metadata" omits some base API functions.
$MSApiClient.SupportedApiFunctions = ($API_SUPPORTEDFUNCTIONS.Substring(0,$API_SUPPORTEDFUNCTIONS.Length-1) + "," + $SupportedApiFunctions.Substring(1) ) | ConvertFrom-Json
return $MSApiClient
}
<#
.SYNOPSIS
Sends an API call to the MailStore or SPE Management Server.
.DESCRIPTION
Sends an API call to the MailStore or SPE Management Server.
If the server decides to run the called function asynchronously, this commandlet waits for the final result.
Use <Start-MSApiCall> for asynchronous function handling.
Returns a JSON <PSCustomObject>.
.PARAMETER MSApiClient
MS API client object created by "New-MSApiClient".
.PARAMETER ApiFunction
A valid MS API function.
.PARAMETER ApiFunctionParameters
The parameters for the API function.
Provide as a hashtable, e.g. @{parameter1 = value1; parameter2 = value2; ...},
or PSCustomObject with parameters mapped to properties.
.PARAMETER StatusTimeout
Time in milliseconds until the the server stops waiting for a new status update to send.
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API_Commands
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Function_Reference
.OUTPUTS
A JSON <PSCustomObject> that encapsulates the HTTP response of the MS server.
#>
function Invoke-MSApiCall {
Param(
[Parameter(Mandatory = $True, Position = 1)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$MSApiClient,
[Parameter(Mandatory = $True, Position = 2)]
[ValidateScript({$MSApiClient.SupportedApiFunctions.name.Contains($_)})]
[string]$ApiFunction,
[Parameter(Position = 3)]
[System.Object]$ApiFunctionParameters = @{},
[Parameter(Position = 4)]
[ValidateNotNull()]
[int]$StatusTimeout = 5000
)
return InternalMSApiCall -MSApiClient $MSApiClient -ApiFunction $ApiFunction -ApiFunctionParameters $ApiFunctionParameters -StatusTimeout $StatusTimeout
}
<#
.SYNOPSIS
Sends an API call to the MailStore or SPE Management Server.
.DESCRIPTION
Sends an API call to the MailStore or SPE Management Server.
If the server decides to run the called function asynchronously, this commandlet runs the call as a background job.
Use <Invoke-MSApiCall> for synchronous function handling.
Returns an object that contains information about the result (see Output).
.PARAMETER MSApiClient
MS API client object created by "New-MSApiClient".
.PARAMETER ApiFunction
A valid MS API function.
.PARAMETER ApiFunctionParameters
The parameters for the API function.
Provide as a hashtable, e.g. @{parameter1 = value1; parameter2 = value2; ...},
or PSCustomObject with parameters mapped to properties.
.PARAMETER StatusTimeout
Time in milliseconds until the the server stops waiting for a new status update to send.
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API_Commands
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Function_Reference
.OUTPUTS
A JSON <PSCustomObject> that encapsulates the HTTP response of the MS server.
If that object's <statusCode> property is "running", a Windows PowerShell background job handles the Status of the server process.
The job fires PSEngineEvents with the status token as SourceIdentifier and the current status in MessageData as a JSON <PSCustomObject>.
Once the job is finished, it returns the final Status as a JSON <PSCustomObject>.
#>
function Start-MSApiCall {
Param(
[Parameter(Mandatory = $True, Position = 1)]
[ValidateNotNullOrEmpty()]
[PSCustomObject]$MSApiClient,
[Parameter(Mandatory = $True, Position = 2)]
[ValidateScript({$MSApiClient.SupportedApiFunctions.name.Contains($_)})]
[string]$ApiFunction,
[Parameter(Position = 3)]
[System.Object]$ApiFunctionParameters = @{},
[Parameter(Position = 4)]
[ValidateNotNull()]
[int]$StatusTimeout = 5000
)
return InternalMSApiCall -MSApiClient $MSApiClient -ApiFunction $ApiFunction -ApiFunctionParameters $ApiFunctionParameters -StatusTimeout $StatusTimeout -RunAsynchronously
}
<#
.SYNOPSIS
Cancels a long running MS server process.
.DESCRIPTION
Cancels a long running MS server process.
Returns an object that contains the Status.
.PARAMETER MSApiClient
MS API client object created by "New-MSApiClient".
.PARAMETER AsyncReturnObject
JSON <PSCustomObject> that encapsulates the initial Status returned by the server in answer to the original API request.
.PARAMETER Token
The Status token returned by the initial API request.
Alternative to AsyncReturnObject.
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#Long_Running_Processes
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#Long_Running_Processes
.LINK
http://en.help.mailstore.com/MailStore_Server_Administration_API#Initial_HTTP_Response
.LINK
http://en.help.mailstore.com/spe/Management_API_-_Using_the_API#Initial_HTTP_Response
.OUTPUTS
JSON <PSCustomObject> that encapsulates the Status returned by the server.
.NOTES
This function sends an API call to the MailStore or SPE Management Server to request a specific long running process to be cancelled.
The server decides if and when the cancellation occurs; it does not necessarily cancel the process immediately.
The background job that does the Status handling continues to run until it receives the server's cancellation signal.
#>
function Stop-MSApiCall {
Param(
[Parameter(Mandatory = $True, Position = 1)]
[ValidateNotNullorEmpty()]
[PSCustomObject]$MSApiClient,
[Parameter(ParameterSetName = "JobByObject", Mandatory = $True, Position = 2)]
[ValidateNotNullorEmpty()]
[PSCustomObject]$AsyncReturnObject,
[Parameter(ParameterSetName = "JobByToken", Mandatory = $True, Position = 2)]
[ValidateNotNullOrEmpty()]
[string]$Token
)
if ($PSCmdlet.ParameterSetName -eq "JobByObject") {
$Token = $AsyncReturnObject.token
}
if ($Token -ne "") {
return Invoke-MSApiCall $MSApiClient "cancel-async" @{token = $Token}
}
}
# Aliases to support MailStore SPE 8.5 scripts
# Start-MSSPEApiCall is mapped to Invoke-MSApiCall to assure the correct behavior
Set-Alias -Name New-MSSPEApiClient -Value New-MSApiClient
Set-Alias -Name Invoke-MSSPEApiCall -Value Invoke-MSApiCall
Set-Alias -Name Start-MSSPEApiCall -Value Invoke-MSApiCall
Set-Alias -Name Stop-MSSPEApiCall -Value Stop-MSApiCall
# Aliases to support MailStore Server 7/8 scripts
# Start-MSSApiCall is mapped to Invoke-MSApiCall to assure the correct behavior
Set-Alias -Name New-MSSApiClient -Value New-MSApiClient
Set-Alias -Name Invoke-MSSApiCall -Value Invoke-MSApiCall
Set-Alias -Name Start-MSSApiCall -Value Invoke-MSApiCall
# Public members that should be visible through Import-Module
Export-ModuleMember -Function New-MSApiClient, Invoke-MSApiCall, Start-MSApiCall, Stop-MSApiCall -Alias New-MSSPEApiClient, Invoke-MSSPEApiCall, Start-MSSPEApiCall, Stop-MSSPEApiCall, New-MSSApiClient, Invoke-MSSApiCall, Start-MSSApiCall

View File

@@ -0,0 +1,292 @@
Function MoveOrCopy-Item-withLogging {
<#
.SYNOPSIS
Function will copy or move File(s).
.DESCRIPTION
If File already exists in target Path new File will get a Version ~2.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
Datei, Datei1, DateiName, DateiEndung, DateiTest, DateiVersion,ZielPath, MoveorCopy, SourcePath
.REQUIREMENT Variables preSet
VersionSeperator
.REQUIREMENT Functions
Write-Logfile
.VERSION
1.2.1.2 / 23.02.2024
.PARAMETER SourceFile
Give the full Path and Filename to one File.
.PARAMETER DestinationPath
Give the Target Path you want to move or copy the specified File.
.PARAMETER Action
Determine which Action you want to perform <Copy|Move>. Default Value is "Copy".
.PARAMETER NewFileName
Give a String, which get the new Name of the File you are moving.
.PARAMETER NewFileName_prefix
Give a String, which get the new prefix Name of the File you are moving.
.PARAMETER NewFileName_suffix
Give a String, which get the new suffix Name of the File you are moving.
.EXAMPLE
MoveOrCopy-Item-withLogging -SourceFile "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy move
.EXAMPLE
MoveOrCopy-Item-withLogging -SourceFile "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy copy
#>
Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage='Give the full Path and Filename to one File.')]
[ValidateNotNullOrEmpty()]
[String]$SourceFile,
[Parameter(Mandatory=$True,HelpMessage='Give the Target Path you want to move or copy the specified File.')]
[ValidateNotNullOrEmpty()]
[String]$DestinationPath,
[Parameter(Mandatory=$True,HelpMessage='Determine which Action you want to perform <Copy|Move>. Default Value is "Copy".')]
[ValidateSet("copy","move")]
[String]$Action="copy",
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName,
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new prefix Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName_prefix,
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new suffix Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName_suffix
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ((Test-Path $SourceFile -PathType Leaf) -eq $True) {
Write-Logfile -LogLine ""
$SourcePath = ([System.IO.Path]::GetDirectoryName($SourceFile).ToString())
$FileName = ([System.IO.Path]::GetFileName($SourceFile).ToString())
$FileName_noExt = ([System.IO.Path]::GetFileNameWithoutExtension($SourceFile).ToString())
$FileExtension = ([System.IO.Path]::GetExtension($SourceFile).ToString())
IF (!$VersionSeperator) {
Write-Logfile -LogLine "ERROR: Wrong Function call."
Write-Logfile -LogLine "INFO: Variable VersionSeperator is not valid."
Write-Logfile -LogLine "Application was unplannd terminated."
EXIT
} #end if
IF ($newfilename) {
Write-Logfile -LogLine "New Filename ($newfilename) will replace the old one."
Set-Variable -Name Filename -Value ($newfilename+$FileExtension)
Set-Variable -Name Filename_noExt -Value ($newfilename)
} #end if
IF ($newfilename_prefix) {
Write-Logfile -LogLine "New prefix ($newfilename_prefix) has been set for file."
Set-Variable -Name Filename -Value (($newfilename_prefix+$FileSeperator+$Filename) -replace "$FileSeperator$FileSeperator","$FileSeperator")
Set-Variable -Name Filename_noExt -Value (($newfilename_prefix+$FileSeperator+$Filename_noExt) -replace "$FileSeperator$FileSeperator","$FileSeperator")
} #end if
IF ($newfilename_suffix) {
Write-Logfile -LogLine "New suffix ($newfilename_suffix) has been set for file."
Set-Variable -Name FileName -Value (($Filename -split "$VersionSeperator")[0])
Set-Variable -Name FileName_noExt -Value (($Filename_noExt -split "$VersionSeperator")[0])
Set-Variable -Name Filename -Value (($Filename_noExt+$FileSeperator+$newfilename_suffix+$FileExtension) -replace "$FileSeperator$FileSeperator","$FileSeperator")
Set-Variable -Name Filename_noExt -Value (($Filename_noExt+$FileSeperator+$newfilename_suffix) -replace "$FileSeperator$FileSeperator","$FileSeperator")
} #end if
# Does file already exist in the target directory?
$FileTest = Test-Path "$DestinationPath\$FileName" -PathType Leaf
IF ($Filetest -eq $True) {
Write-Logfile -LogLine "The File ($Filename) already exists in the target directory, starting Version Check."
[String]$FileNameSplit = ($Filename_noExt -split $VersionSeperator)
[Int]$FileVersion = 0
IF ($FileNameSplit[1] -is [Int]) {
[Int]$FileVersion = $FileNameSplit[1]
} #end if
# Has the new file already a Version tag?
IF ($FileVersion -eq 0) {
Write-Host "DEBUG Info: Sourcefile includes no VersionSeperator."
# To skip Version ~1.
$FileVersion++
} #end if
ELSE {
Write-Host "DEBUG Info: Sourcefile includes VersionSeperator."
$FileName_noExt = $FilenameSplit[0]
} #end else
DO {
Write-Host "DEBUG Info: Count file version:" $FileVersion; $FileVersion++
}
WHILE (($Filetest = Test-Path -Path "$DestinationPath\$FileName_noExt$VersionSeperator$FileVersion$FileExtension") -eq 'True')
# code block for the copy or move process
Try {
Set-Variable -Name FileHash_befor -Value (Get-FileHash -Path "$SourceFile" -Algorithm SHA512 | Select-Object Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Set-Variable -Name FileTemp -Value (Copy-Item -Path "$SourceFile" -Destination "$DestinationPath\$Timestamp3`_$FileName" -PassThru -Force)
Write-Logfile -LogLine "The $Action command has been completed."
Set-Variable -Name FileFinal -Value (Rename-Item -Path "$FileTemp" -NewName "$FileName_noExt$VersionSeperator$FileVersion$FileExtension" -PassThru -Force )
Write-Logfile -LogLine "File was renamed to: $FileName_noExt$VersionSeperator$FileVersion$FileExtension, and is now transferd to: $DestinationPath."
Set-Variable -Name FileHash_after -Value (Get-FileHash -Path "$FileFinal" -Algorithm SHA512 | Select-Object Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Write-Host "DEBUG Info: Hash Value before: $FileHash_befor"
Write-Host "DEBUG Info: Hash Value after: $FileHash_after"
IF ($Action -eq 'move') {
Write-Host "DEBUG Info: Moving action was choosen, will delete source file."
IF ($FileHash_befor -eq $FileHash_after) {
Try {
Remove-Item -Path "$SourceFile" -Force
} #end try
Catch {
Write-Logfile -LogLine "Error removing the source file."
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "HASH Value does mismatch!"
Write-Logfile -LogLine "Aborting delete operation!"
} #end else
} #end if
Return $FileFinal.Fullname
} #end try
Catch {
Write-Logfile -LogLine "Error at $Action command, processing file: $SourceFile"
Write-Logfile -LogLine "Please check your privileges"
exit
} #end catch
} #end if
ELSE {
Set-Variable -Name FileHash_befor -Value (Get-FileHash -Path "$SourceFile" -Algorithm SHA512 | Select-Object Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Set-Variable -Name FileFinal -Value (Copy-Item -Path "$SourceFile" -Destination "$DestinationPath\$FileName" -PassThru -Force)
Set-Variable -Name FileHash_after -Value (Get-FileHash -Path "$FileFinal" -Algorithm SHA512 | Select-Object Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Write-Logfile -LogLine "The $Action command has been completed for file: $SourceFile"
Write-Logfile -LogLine "And is now transferd to: $DestinationPath"
Write-Host "DEBUG Info: Hash Value before: $FileHash_befor"
Write-Host "DEBUG Info: Hash Value after: $FileHash_after"
IF ($Action -eq 'move') {
Write-Host "DEBUG Info: Moving action was choosen, will delete source file."
IF ($FileHash_befor -eq $FileHash_after) {
Try {
Remove-Item -Path "$SourceFile" -Force
} #end try
Catch {
Write-Logfile -LogLine "Error removing the source file."
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "HASH Value does mismatch!"
Write-Logfile -LogLine "Aborting delete operation!"
} #end else
} #end if
ELSEIF ($Action -eq 'copy') {
Write-Host "DEBUG Info: Coping action was choosen, will not delete original file."
} #end elseif
Return $FileFinal.Fullname
} #end else
} #end if
ELSE {
Write-LogFile -LogLine "Cannot find Source File!"
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,114 @@
Function Remove-Item-withLogging {
<#
.SYNOPSIS
Function will delete Items selected by Path, Name and Age.
.DESCRIPTION
Function will delete Items selected by Path, Name and Age, with logging this.
For a successful performed deletion, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Variables
Path, FileKeepTime, FileBaseName, Item, Items
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
Number: 1.2.0.0 / Date: 25.06.2025
.PARAMETER Path
Give the Full Path, where the Item(s) located, which should be deleted.
.PARAMETER FileKeepTime
Give the time in Days, which Items should be deleted, which are older than...
.PARAMETER FileBaseName
Give the <Filename> which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.
.PARAMETER FileExtension
Give the FileExtension which Files will be selected for deletion (Default: log).
.EXAMPLE
Remove-Item-withLogging -Path "E:\LogFiles" -FileKeepTime 5 -FileBaseName Filename
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the Full Path, where the Item(s) located, which should be deleted.')]
[ValidateNotNullOrEmpty()]
[String]$Path=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the time in Days, which Item(s) should be deleted, which are older than...')]
[ValidateRange(0,1000)]
[Int]$FileKeepTime=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the Filename which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.')]
[ValidateNotNullOrEmpty()]
[String]$FileBaseName=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Give the FileExtension which Files will be selected for deletion (Default: log).')]
[ValidateNotNullOrEmpty()]
[String]$FileExtension="log"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ($FileKeepTime -gt 0) {
Write-Logfile -LogLine "Files should be removed which are older than $FileKeepTime Day(s)."
[Array]$Items = (Get-ChildItem -Path "$Path\*" -Filter *.$FileExtension | where {$_.Name -like "*$FileBaseName*" -and $_.lastwritetime -lt $((Get-Date).AddDays(-$FileKeepTime)) -and -not $_.psiscontainer})
IF ($Items.count -le 0) {
Write-Logfile -LogLine "Found no old Files."
Return $False
} ELSE {
Write-Logfile -LogLine "Deleting old Files (Found: $($Items.count)) :"
Try {
$Items | Remove-Item -Force -Verbose -ErrorAction Stop
Write-Logfile -LogLine "Files were removed!"
Return $True
} Catch {
Write-Logfile -LogLine "Cannot remove Files!"
Write-Logfile -LogLine "Please check your privileges!"
Return $False
} #end catch
} #end else
} ELSE {
Write-Logfile -LogLine "You disabled File deletion, they all will be kept."
Return $False
} #end else
} ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,367 @@
Function Restart-windreamClient-withLogging {
<#
.SYNOPSIS
Restart windream Client Components via COM Interface
.DESCRIPTION
If Connection to the windream Server gets interrupted (network loss, eg.), it is neccessery to restart the Client Components.
Otherwise you can Stop or Start Client Components with this Function.
For a successful performed Action, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V3, windream Client Connectivity (>=V3.6)
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
windreamControlCenter, windreamIndexService, ServiceTest, Action
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
1.2.0.0 / 28.09.2018
.PARAMETER Action
Determine which Action you want to perform <Stop|Restart|Start>. Default Value is <Restart>.
.PARAMETER ServiceTest
Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.
.PARAMETER StartTimeout
.EXAMPLE
Restart-windreamClient
.EXAMPLE
Restart-windreamClient -Action Start
.EXAMPLE
Restart-windreamClient -Action Start -ServiceTest $False
#>
Param (
[Parameter(Position=0,Mandatory=$False,HelpMessage='Determine which Action you want to perform <Stop|Restart|Start>. Default Value is "Restart".')]
[ValidateSet("Stop","Restart","Start")]
[String]$Action="Restart",
[Parameter(Position=1,Mandatory=$False,HelpMessage='Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.')]
[ValidateSet($True,$False)]
[Switch]$ServiceTest=$True,
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the Timeout limit in Seconds for the windream Start/Restart procedure, ValidateRange(1 - 300). Default Value is "10".')]
[ValidateRange(1,300)]
[INT]$StartTimeout=10
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Host "DEBUG Info: Write-LogFile - Module exists."
#If Servie Test was enabled (by default true) check if windream vfs Service is running
IF ($ServiceTest -eq $True) {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is enabled!"
#Check if windream vfs Service is installed
Try {
[Object]$ServiceTest = $NULL
[Object]$ServiceTest = Get-Service -Name vfssvc -ErrorAction Stop
Write-LogFile -LogLine "Found Service: vfssvc"
Write-LogFile -LogLine "Service is currently: $((Get-Service -Name vfssvc).Status)"
} #end try
Catch {
Write-LogFile -LogLine "WARNING: windream Client seems not to be installed completely."
Write-LogFile -LogLine "Missing Service: vfssvc"
} #end catch
} #end if
#If Servie Test is disabled
ELSE {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is disabled!"
} #end else
#Try to create windream Objects
Try {
[Object]$windreamControlCenter = New-Object -ComObject "Wmcc.ControlCenter" -ErrorAction Stop
[Object]$windreamIndexService = New-Object -ComObject "WMIndexServer.WMIdxSvControl" -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Wmcc.ControlCenter or WMIndexServer.WMIdxSvControl!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#If Function was called to Stop windream Client Components
IF ($Action -like "Stop") {
Write-LogFile -LogLine "Stop windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
$windreamControlCenter.ExitCC(0) | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end if
#If Function was called to Restart windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Restart windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called invalid Values, which should be not possible be the ValidateSet of the Function Parameters
ELSE {
Write-Logfile -LogLine "Function Call went wrong, please check the ValidateSet"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,367 @@
Function Restart-windreamClient-withLogging {
<#
.SYNOPSIS
Restart windream Client Components via COM Interface
.DESCRIPTION
If Connection to the windream Server gets interrupted (network loss, eg.), it is neccessery to restart the Client Components.
Otherwise you can Stop or Start Client Components with this Function.
For a successful performed Action, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V3, windream Client Connectivity (>=V3.6)
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
windreamControlCenter, windreamIndexService, ServiceTest, Action
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
1.2.0.0 / 28.09.2018
.PARAMETER Action
Determine which Action you want to perform <Stop|Restart|Start>. Default Value is <Restart>.
.PARAMETER ServiceTest
Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.
.PARAMETER StartTimeout
.EXAMPLE
Restart-windreamClient
.EXAMPLE
Restart-windreamClient -Action Start
.EXAMPLE
Restart-windreamClient -Action Start -ServiceTest $False
#>
Param (
[Parameter(Position=0,Mandatory=$False,HelpMessage='Determine which Action you want to perform <Stop|Restart|Start>. Default Value is "Restart".')]
[ValidateSet("Stop","Restart","Start")]
[String]$Action="Restart",
[Parameter(Position=1,Mandatory=$False,HelpMessage='Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.')]
[ValidateSet($True,$False)]
[Switch]$ServiceTest=$True,
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the Timeout limit in Seconds for the windream Start/Restart procedure, ValidateRange(1 - 300). Default Value is "10".')]
[ValidateRange(1,300)]
[INT]$StartTimeout=10
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Host "DEBUG Info: Write-LogFile - Module exists."
#If Servie Test was enabled (by default true) check if windream vfs Service is running
IF ($ServiceTest -eq $True) {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is enabled!"
#Check if windream vfs Service is installed
Try {
[Object]$ServiceTest = $NULL
[Object]$ServiceTest = Get-Service -Name vfssvc -ErrorAction Stop
Write-LogFile -LogLine "Found Service: vfssvc"
Write-LogFile -LogLine "Service is currently: $((Get-Service -Name vfssvc).Status)"
} #end try
Catch {
Write-LogFile -LogLine "WARNING: windream Client seems not to be installed completely."
Write-LogFile -LogLine "Missing Service: vfssvc"
} #end catch
} #end if
#If Servie Test is disabled
ELSE {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is disabled!"
} #end else
#Try to create windream Objects
Try {
[Object]$windreamControlCenter = New-Object -ComObject "Wmcc.ControlCenter" -ErrorAction Stop
[Object]$windreamIndexService = New-Object -ComObject "WMIndexServer.WMIdxSvControl" -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Wmcc.ControlCenter or WMIndexServer.WMIdxSvControl!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#If Function was called to Stop windream Client Components
IF ($Action -like "Stop") {
Write-LogFile -LogLine "Stop windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
$windreamControlCenter.ExitCC(0) | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end if
#If Function was called to Restart windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Restart windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Wait-Process -Timeout $StartTimeout | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called invalid Values, which should be not possible be the ValidateSet of the Function Parameters
ELSE {
Write-Logfile -LogLine "Function Call went wrong, please check the ValidateSet"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,211 @@
Function Start-SQLDB-Query-withLogging {
<#
.SYNOPSIS
Function will send a SQL Query to a SQL DB.
.DESCRIPTION
Function will send a SQL Query to a SQL DB. If you set a read command (SELECT ...), function will return a dataset.
.REQUIREMENT General
PowerShell V2 and Function "Write-Logfile".
.REQUIREMENT Variables
DBSQLQuery, DBSQLQueryType, DBSQLConnectServer, DBSQLConnectUser, DBSQLConnectPassword, DBSQLConnectDatabase, DBSQLConnectIntegratedSecurity, DBSQLCommand, DBSQLAdapter, DBSQLConnection
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.0.1.0 / Date: 24.09.2017
.PARAMETER DBSQLQuery
Give a Standard T-SQL Query
.PARAMETER DBSQLQueryType
Give read or write, depends on your planned action ("select" is only read, "insert" and "update" are write)
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType read -DBSQLQuery "SELECT * from TABLE;"
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "INSERT INTO TABLE (column1,column2,column3) VALUES ('Text1', Zahl1, Zahl2) WHERE column4 = 'Text2';"
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "UPDATE TABLE SET column1='Text1',column2=Zahl1,column3=Zahl2 WHERE column4 = 'Text2';"
#>
Param (
[Parameter(Position=0,Mandatory=$False,HelpMessage='Give the SQL Servername or Server name incl. Instance name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectServer=(Get-Variable -Name DBSQLConnectServer -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=1,Mandatory=$False,HelpMessage='Give the database user name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectUser=(Get-Variable -Name DBSQLConnectUser -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the database user password')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectPassword=(Get-Variable -Name DBSQLConnectPassword -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=3,Mandatory=$False,HelpMessage='Give the database name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectDatabase=(Get-Variable -Name DBSQLConnectDatabase -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=4,Mandatory=$False,HelpMessage='Determ if current login credentials should be used for database login ()')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectIntegratedSecurity=(Get-Variable -Name DBSQLConnectIntegratedSecurity -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=5,Mandatory=$True,HelpMessage='Specify the SQL Query')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLQuery,
[Parameter(Position=6,Mandatory=$False,HelpMessage='Determ if Query was for read or write operations')]
[ValidateSet("read","write")]
[STRING]$DBSQLQueryType='read',
[Parameter(Position=7,Mandatory=$False,HelpMessage=')')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLErrorAction='continue'
) #end param ValueFromPipeline=$True
IF (Get-Module -Name "Write-LogFile") {
Write-Logfile -LogLine ""
Write-Logfile -LogLine "Connecting with DB:"
Write-Logfile -LogLine "Server = $DBSQLConnectServer, uid=$DBSQLConnectUser, pwd=<set in ConfigFile>, Database = $DBSQLConnectDatabase, Integrated Security = $DBSQLConnectIntegratedSecurity"
Try {
$DBSQLConnection = New-Object System.Data.SqlClient.SqlConnection
$DBSQLConnection.ConnectionString = "Server = $DBSQLConnectServer; uid=$DBSQLConnectUser; pwd=$DBSQLConnectPassword; Database = $DBSQLConnectDatabase; Integrated Security = $DBSQLConnectIntegratedSecurity"
Write-Logfile -LogLine "Processing SQL Query:"
Write-Logfile -LogLine $DBSQLQuery
IF ($DBSQLQueryType -eq 'read') {
Try {
$DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand
$DBSQLCommand.CommandText = $DBSQLQuery
$DBSQLCommand.Connection = $DBSQLConnection
$DBSQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$DBSQLAdapter.SelectCommand = $DBSQLCommand
$DBSQLDataSet = New-Object System.Data.DataSet
$DBSQLConnection.Open()
$DBSQLAdapter.Fill($DBSQLDataSet)
$DBSQLConnection.Close()
Write-Logfile -Logline "SQL Query result with $($DBSQLDataSet.Tables[0].Rows.Count) row(s)."
#$DBSQLDataSet.Tables[0].Rows | Out-GridView
Return $DBSQLDataSet
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to process SQL Query (read)!"
IF ($ErrorAction -eq 'continue') {
Write-Logfile -LogLine "Program will continue, anyway."
} #end if
ELSEIF ($ErrorAction -eq 'stop') {
Write-Logfile -LogLine "Program will stop."
exit
} #end elseif
ELSE {
Write-Logfile -LogLine "Invalid Value for Parameter DBSQLErrorAction detected."
Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'."
Write-Logfile -LogLine "Program will continue, anyway."
} #end else
} #end catch
} #end if
ELSEIF ($DBSQLQueryType -eq 'write') {
Try {
$DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand
$DBSQLCommand.CommandText = $DBSQLQuery
$DBSQLCommand.Connection = $DBSQLConnection
$DBSQLConnection.Open()
$DBSQLCommand.ExecuteNonQuery()
$DBSQLConnection.Close()
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to process SQL Query (write)!"
IF ($ErrorAction -eq 'continue') {
Write-Logfile -LogLine "Program will continue, anyway."
} #end if
ELSEIF ($ErrorAction -eq 'stop') {
Write-Logfile -LogLine "Program will stop."
exit
} #end elseif
ELSE {
Write-Logfile -LogLine "Invalid Value for parameter DBSQLErrorAction detected."
Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'."
Write-Logfile -LogLine "Program will continue, anyway."
} #end else
} #end catch
} #end elseif
ELSE {
Write-Logfile -LogLine "ERROR: Invalid parameter for function!"
} #end else
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to etablish a DB Connection!"
} #end catch
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,351 @@
Function Start-windreamSession-withLogging {
<#
.SYNOPSIS
Start a connection / Session with a windream Server.
.DESCRIPTION
To work in or with windream, you need to start a Session with a windream Server, to access its files, folders and indices.
The windream Drive letter which was retrived by running this module, will be set for the whole Script.
For Impersonation Login Methode, all these Parameters must be set: windreamServer, windreamDomain, windreamUserName and windreamUserPassword.
Function returns with the whole windreamSession Object if connection was successfully established, otherwise with a $False.
.REQUIREMENT General
PowerShell V3, windream Client Connectivity (>=V3.6)
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
windreamServer, windreamVersion, windreamServerBrowser, windreamConnect, windreamSession, windreamDriveLetter, windreamDriveLetterMapping, PathTest
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
1.2.0.0 / 02.12.2016
.PARAMETER windreamServer
Optional Parameter. Give Server Name of a specific windream Server, you want to connect with. Otherwise default will be choosen.
.PARAMETER windreamDomain
Optional Parameter. Give a Windows Domain (which is windream autorisiered) for Impersonation Login Methode. Otherwise current domain will be choosen.
.PARAMETER windreamUserName
Optional Parameter. Give a Windows User Name (who is windream autorisiered) for Impersonation Login Methode. Otherwise current User Name will be choosen.
.PARAMETER windreamUserPassword
Optional Parameter. Give the Password for the User name you set bevor in $windreamUserName for Impersonation Login Methode.
.PARAMETER windreamVersion
Optional Parameter. Give the minimum Version of windream, to make sure later function calls will work (Example 3.6, 4.0, ...).
.PARAMETER windream64Bit
Optional Parameter. Available since windream 6.0. Necessary, if following functions need 64Bit Integer Support (eg. GetWMObjectByIdEx64(WMEntity aWMEntity, int64 aWMObjectId)).
.PARAMETER windreamDriveLetterMapping
Optional Parameter. If windream Drive Letter was set in the windream Client config, call this Parameter using $true, to check the Mapping in the Windows Explorer. Default Value is "$True".
.EXAMPLE
Start-windreamSession
.EXAMPLE
Start-windreamSession -windreamVersion "3.6" -windream64Bit <$True|$False>
.EXAMPLE
Start-windreamSession -windreamServer <ServerName> -windreamDomain <domain.local> -windreamUserName <UserName> -windreamUserPassword <UserPassword>
.EXAMPLE
Start-windreamSession -windreamVersion "3.6" -windream64Bit <$True|$False> -windreamServer <ServerName> -windreamDomain <domain.local> -windreamUserName <UserName> -windreamUserPassword <UserPassword>
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give Server Name of a specific windream Server, you want to connect with. Otherwise default will be choosen.')]
[AllowEmptyString()]
[String]$windreamServer=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give a Windows Domain (which is windream autorisiered) for Impersonation Login Methode. Otherwise current domain will be choosen.')]
[ValidateNotNullOrEmpty()]
[String]$windreamDomain=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give a Windows User Name (who is windream autorisiered) for Impersonation Login Methode. Otherwise current User Name will be choosen.')]
[ValidateNotNullOrEmpty()]
[String]$windreamUserName=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give the Password for the User name you set bevor in $windreamUserName for Impersonation Login Methode.')]
[ValidateNotNullOrEmpty()]
[String]$windreamUserPassword=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give the minimum Version of windream, to make sure later function calls will work (Example 3.6, 4.0, ...). Default Value is 4.0.')]
[ValidateNotNullOrEmpty()]
[String]$windreamVersion="4.0",
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Available since windream 6.0. Necessary, if following functions need 64Bit Integer Support (eg. GetWMObjectByIdEx64(WMEntity aWMEntity, int64 aWMObjectId)). Default Value is $False')]
[ValidateSet($True,$False)]
[Switch]$windream64Bit=$False,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. If windream Drive Letter was set in the windream Client config, call this Parameter using $true, to check the Mapping in the Windows Explorer. Default Value is "$True".')]
[ValidateSet($True,$False)]
[Switch]$windreamDriveLetterMapping=$True
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Host "DEBUG Info: Write-LogFile - Module exists."
#If Function was called without an explicite windream Server, try to get the default
IF (!$windreamServer) {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Function was called without a specific windream Server,"
Write-Logfile -LogLine "trying to find the default windream Server."
Try {
$windreamServerBrowser = New-Object -ComObject "WMOBrws.ServerBrowser" -ErrorAction Stop
$windreamServer = $windreamServerBrowser.GetCurrentServer()
Write-Logfile -LogLine "windream Server is: $windreamServer"
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOBrws.ServerBrowser!"
Write-Logfile -LogLine "And/Or unable the retrieve default windream Server!"
$windreamServer = $NULL
} #end catch
} #end if
#If Function was called with an explicite windream Server
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Function was called with specific windream Server, trying to connect to $windreamServer"
Write-Logfile -LogLine "Remember: Since windream 4.0, this will only work if you are using Impersonation Login Methode."
Write-LogFile -Logline "windreamServer, windreamDomain, windreamUserName and windreamUserPassword"
Try {
$windreamServerBrowser = New-Object -ComObject "WMOBrws.ServerBrowser" -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOBrws.ServerBrowser!"
Return $False
} #end catch
} #end else
#Go ahead if windreamServer is not null and is reachable via network ping
IF (($windreamServer) -and (Test-Connection -ComputerName $windreamServer -Count 1 -ErrorAction SilentlyContinue)) {
Try {
$windreamConnect = New-Object -ComObject "Windream.WMConnect" -ErrorAction Stop
$windreamConnect.MinReqVersion = $windreamVersion
$windreamConnect.ClientSupports64BitID = $windream64Bit
Write-Logfile -LogLine "windream Connect created!"
} # end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Windream.WMSession!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Try {
$windreamSession = New-Object -ComObject "Windream.WMSession" #-ErrorAction Stop
Write-Logfile -LogLine "windream Session created!"
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Windream.WMSession!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Use Impersonation Login methode, if these three Parameters are set (-gt $NULL).
IF (($windreamUserName) -and ($windreamUserPassword) -and ($windreamDomain)) {
Try {
$windreamConnect.ModuleId = 9
$windreamImpersonation = New-Object -ComObject "WMOTool.WMUserIdentity" -ErrorAction Stop
$windreamImpersonation.aDomain = $windreamDomain
$windreamImpersonation.aPassword = $windreamUserPassword
$windreamImpersonation.aServerName = $windreamServer
$windreamImpersonation.aUserName = $windreamUserName
Try {
Write-Logfile -LogLine "Try to Login Impersonation"
$windreamSession = $windreamConnect.Login($windreamImpersonation)
} #end try
Catch {
Write-Logfile -LogLine "Cannot Login into windream Session!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOTool.WMUserIdentity!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
#If Impersonation Login methode was not set, try to login with current username, domain and password
ELSE {
Try {
Write-Logfile -LogLine "Try to Login with current credentials."
$windreamConnect.LoginSession($windreamSession)
} #end try
Catch {
Write-Logfile -LogLine "Cannot Login into windream Session!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end else
IF ($windreamSession.aLoggedin -eq $True) {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Connection established"
Write-Logfile -LogLine "You are connected with $($windreamConnect.ServerName) as $($windreamSession.aUser.aName)"
Write-Host "DEBUG Info: Do not forget to Logout Session after finished work."
$windreamDriveLetter = $windreamServerBrowser.GetServerValue($windreamServer, "DriveLetter", 0)
IF ($windreamDriveLetter) {
Write-Logfile -LogLine "The configured windream Drive Letter is: $windreamDriveLetter"
Set-Variable -Name windreamDriveLetter -Value $windreamDriveLetter -Scope Global -ErrorAction SilentlyContinue
$PathTest = Test-Path -Path "$windreamDriveLetter`:\" -PathType Container
IF ($PathTest -eq $True) {
Write-Logfile -LogLine "The configured windream Drive Letter seems to be connected, as well!"
} #end if
ELSE {
Write-Logfile -LogLine "The configured windream Drive Letter seems not to be connected!"
IF ($windreamDriveLetterMapping -eq $True) {
Try {
Write-Logfile -LogLine "Try to connect the windream Drive ..."
Remove-PSDrive -Name "$windreamDriveLetter" -Force -Scope Global -ErrorAction SilentlyContinue
$PathTest = New-PSDrive -Name "$windreamDriveLetter" -PSProvider FileSystem -Root "\\windream\objects" -Persist -Scope Global -ErrorAction Stop
Write-Logfile -LogLine "windream Drive Letter $PathTest should be connected, now!"
} #end try
Catch {
Write-Logfile -LogLine "Cannot map the windream Drive!"
Set-Variable -Name windreamDriveLetter -Value $NULL -Scope Global -ErrorAction SilentlyContinue
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "Will not try to map the windream Drive..."
} #end else
} #end else
} #end if
ELSE {
Write-Logfile -LogLine "WARNING: There is no windream Drive Letter configured."
Write-Logfile -LogLine "This could cause access problems!"
Write-Logfile -LogLine "Please check your windream Alias Settings!"
} #end else
Return $windreamSession
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Connection refused"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
#Stop if windream Server was unavailable
ELSE {
Write-Logfile -LogLine "Cannot retrieve windream Server to connect with or test connection failed!"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,167 @@
Function Test-FileState-withLogging {
<#
.SYNOPSIS
Function will check if given File is accessible.
.DESCRIPTION
This Function will check the accessibility of a File.
If the given File was readable, Function will Return "readable"
Additional Function can be called with the Parameter "-Action writetest",
then after a successful readtest, there will be a writetest.
On Success Return Value will be "writeable".
If File doesn exist Function will return $NULL.
If File Attribute was not editable (by resetting them),
Function will return "noteditable".
.REQUIREMENT General
PowerShell V3
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
SourceFile, SourceFileAttributeReset, Action, FileInfo, FileCheckResult, FileStream
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.1.0.0 / Date: 21.03.2017
.PARAMETER SourceFile
Give the full Path and Filename you want to check.
.PARAMETER SourceFileAttributeReset
Set on $True, if Function should reset the File Attributes (if ReadOnly was set). Default Value is $True.
.PARAMETER Action
Determine which Action you want to perform <readtest|writetest>. Default Value is "readtest".
.EXAMPLE
Test-FileState-withLogging -SourceFile "E:\Path\file_to_check.txt"
.EXAMPLE
Test-FileState-withLogging -SourceFile "E:\Path\file_to_check.txt" -Action writetest
#>
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the full Path and Filename you want to check.')]
[ValidateNotNullOrEmpty()]
[String]$SourceFile,
[Parameter(Mandatory=$False,HelpMessage='Set on $True, if Function should reset the File Attributes (if ReadOnly was set). Default Value is $True.')]
[ValidateSet($True,$False)]
[Switch]$SourceFileAttributeReset=$True,
[Parameter(Mandatory=$False,HelpMessage='Determine which Action you want to perform <readtest|writetest>. Default Value is "readtest".')]
[ValidateSet("readtest","writetest")]
[String]$Action="readtest"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ((Test-Path -Path $SourceFile) -eq 'True') {
$FileInfo = (New-Object System.IO.FileInfo $SourceFile)
$FileCheckResult = "unknown"
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Checking if file: $SourceFile is locked/readonly..."
IF (($FileInfo.Attributes -match "ReadOnly") -and ($SourceFileAttributeReset -eq $True)) {
Write-Host "DEBUG Info: ReadOnly Attribute found, removing if possible"
Try {
$FileInfo.Attributes="Archive","Temporary"
Write-Host "DEBUG Info: File Attributes has been recessed!"
} #end try
Catch {
Write-Logfile -LogLine "WARNING: Cannot recessed File Attributes!"
Return "noteditable"
} #end catch
} #end if
Write-Logfile -LogLine "Checking if file: $SourceFile is readable."
# Check if file is readable
Try {
$FileStream = $FileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read)
Write-Host "DEBUG Info: Is file readable?" $FileStream.CanRead
$FileStream.Close()
$FileCheckResult = "readable"
} #end try
Catch {
Write-Logfile -LogLine "File: $SourceFile is not even readable."
Write-Host "DEBUG Info: Is file readable?" $FileStream.CanRead
$FileCheckResult = "notreadable"
} #end catch
# Check if file is writeable
IF (($FileCheckResult -eq "readable") -and ($Action -eq 'writetest')) {
Write-Logfile -LogLine "Checking if file: $SourceFile is writeable."
Try {
$FileStream = $FileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Write)
Write-Host "DEBUG Info: Is file writeable?" $FileStream.CanWrite
$FileStream.Close()
$FileCheckResult = "writeable"
} #end try
Catch {
Write-Logfile -LogLine "File: $SourceFile is not writeable."
Write-Host "DEBUG Info: Is file writeable?" $FileStream.CanWrite
$FileCheckResult = "notwriteable"
} #end catch
} #end if
Write-Logfile -LogLine "File $SourceFile checked with result: $FileCheckResult"
Return $FileCheckResult
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Given file: $SourceFile seems not to exist, or access is denied."
Return $NULL
} #end else
} #end if
ELSE {
Write-Host " "
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,114 @@
Function Test-Path-withLogging {
<#
.SYNOPSIS
Function will check the given Path for existence.
.DESCRIPTION
If Path doesn´t exist, Function will try to create it.
You can disable the create Function by calling with "-Action "ignore"".
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
Path, PathTest
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.0.1.0 / Date: 17.12.2016
.PARAMETER Path
Give the full Path you want to check or create.
.PARAMETER Action
Determine which Action you want to perform <create|ignore". Default Value is "create".
.EXAMPLE
Test-Path-withLogging -Path "E:\Path\to\create"
.EXAMPLE
Test-Path-withLogging -Path "E:\Path\to\check" -Action "ignore"
#>
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the full Path you want to check.')]
[ValidateNotNullOrEmpty()]
[String]$Path,
[Parameter(Mandatory=$False,HelpMessage='Determine which Action you want to perform <create|ignore". Default Value is "create".')]
[ValidateSet("create","ignore")]
[String]$Action="create"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Checking Path $Path for existence."
$PathTest = Test-Path -PathType Container $Path
#If given Path already exists
IF ($PathTest -eq "True") {
Write-Logfile -LogLine "Path $Path already exists and can be used."
Return $True
} #end if
#If given Path does not exist
ELSE {
Write-Logfile -LogLine "Path $Path does not exist."
IF ($Action -eq "create") {
Try {
Write-Logfile -LogLine "Path $Path has to been created."
New-Item -Path $Path -ItemType directory -Force -ErrorAction Stop
Return $True
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to create Path."
Write-Logfile -LogLine "INFO: Maybe there is an access or rights Problem."
Return $False
} #end catch
} #end if
ELSE {
Return $False
} #end else
} #end else
} #end if
ELSE {
Write-Host " "
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,232 @@
Function Write-LogFile {
<#
.SYNOPSIS
Function will write a given String to a Logfile.
.DESCRIPTION
Just like the cmdlet Write-Host, this Function will display Output on the Console.
Parallel Output will be written into a designated LogFile.
It is recommended to init the LogPath Variable with $Null and the LogPaths Variable with a possible Path,
which has to be checked for accessible.
This is important, because if given Path was inaccessible (-> Access Test failed), Function will try some other Paths for accessible.
These are: The ScriptPath (\Logs) from, which triggerd this Function and $env:temp\Digital Data\$ScriptName\Logs.
After a successful Access Test, Function will set the Variable LogPath, with the first accessible Path tested.
Function will not give any Return Values, because if it is impossible to write a LogFile, Function will force the whole Script to exit.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
PathTest, FileTest, LogPaths, Counter1, LogLine
.REQUIREMENT Variables preSet
LogFile, LogPath, ScriptName, ScriptPath
.REQUIREMENT Functions
<NONE>
.VERSION
Number: 2.1.0.1 / Date: 23.09.2017
.PARAMETER LogLine
Give the String you want to be written into the Logfile.
.EXAMPLE
Write-LogFile -LogLine "Write this in my Log, please."
.EXAMPLE
Write-LogFile -LogLine "Write this Variabel $Variable in my Log, please."
#>
Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage='Give the String you want to be written into the Logfile.')]
[AllowEmptyString()]
[STRING]$LogLine,
[Parameter(Position=1,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$LogFile=(Get-Variable -Name LogFile -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$LogPath=(Get-Variable -Name LogPath -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=3,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$ScriptName=(Get-Variable -Name ScriptName -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=4,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$ScriptPath=(Get-Variable -Name ScriptPath -Scope Global -ValueOnly -ErrorAction SilentlyContinue)
) #end param
#Clear Error Variable
$error.clear()
IF (!$LogFile) {
$LogFile = ((($MyInvocation.MyCommand.Name) -split "\.")[0].ToString())+".log"
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for LogFile, was set to: $LogFile"
} #end if
IF (!$LogPath) {
$LogPath = $PSScriptRoot+"\Logs"
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for LogPath, was set to: $LogPath"
} #end if
IF (!$ScriptName) {
$ScriptName = ((($MyInvocation.MyCommand.Name) -split "\.")[0].ToString())
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for ScriptName, was set to: $ScriptName"
} #end if
IF (!$ScriptPath) {
$ScriptPath = $PSScriptRoot
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for ScriptPath, was set to: $ScriptPath"
} #end if
# This if / else block is only for determine the LogPath
IF ((!$LogPath) -or ($LogPath -eq $PSScriptRoot+"\Logs")) {
Write-Host ""
Write-Host "DEBUG Info - Write-LogFile: LogPath is currently not set!"
[Array]$LogPaths = $LogPaths
[Array]$LogPaths = ($LogPaths += "$ScriptPath\Logs","$env:temp\Digital Data\$ScriptName\Logs")
[int]$Counter1 = 0
DO {
#Determine the current Array object
[String]$LogPath = [Array]$($LogPaths[$Counter1])
Write-Host ""
Write-Host "DEBUG Info - Write-LogFile: Testing LogPath: $LogPath"
$PathTest = Test-Path -PathType Container "$LogPath"
#Check if Path already exists
IF ($PathTest -eq $True) {
Write-Host "DEBUG Info - Write-LogFile: LogPath seems already to exists: $LogPath"
} #end if
ELSE {
#If Path doesnt exist, try to create it!
Try {
Write-Host "DEBUG Info - Write-LogFile: Trying to create LogPath: $LogPath"
New-Item -ItemType Directory -Path "$LogPath" -Force -ErrorAction Stop | Out-Null
Write-Host "DEBUG Info - Write-LogFile: Trying seems to be successful!"
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot create LogPath or access denied!"
Write-Host $Error
} #end catch
} #end else
#Check again if path exists
$PathTest = Test-Path -PathType Container "$LogPath"
IF ($PathTest -eq $True) {
Try {
Write-Host "DEBUG Info - Write-LogFile: Trying to write a TestFile into the LogPath."
New-Item -ItemType File -Path "$LogPath\AccessTest.txt" -Force -ErrorAction Stop | Out-Null
Add-content "$LogPath\AccessTest.txt" -Value "This is a Test!" -Force -ErrorAction Stop | Out-Null
$FileTest = Test-Path -Path "$LogPath\AccessTest.txt" -PathType Leaf -ErrorAction Stop
Remove-Item -Path "$LogPath\AccessTest.txt" -Force -ErrorAction Stop | Out-Null
Write-Host "DEBUG Info - Write-LogFile: Write Test seems to be successful."
Set-Variable -Name LogPath -Value $LogPath -Scope Global -Force
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot write into LogPath or access denied!"
Write-Host $Error
} #end catch
} #end if
ELSE {
Write-Host "DEBUG Info - Write-LogFile: Cannot create LogPath or access denied!"
Write-Host $Error
} #end else
[int]$Counter1++ | Out-Null
} #end do
UNTIL ((($PathTest -eq $True) -and ($FileTest -eq $True)) -or ($Counter1 -eq $($LogPaths.count)) )
} #end if
ELSEIF ($LogPath) {
#Write-Host "DEBUG Info - Write-LogFile: LogPath was already been set!"
#Write-Host "DEBUG Info - Write-LogFile: LogPath is $LogPath"
} #end elseif
ELSE {
Write-Host "Unexpected Error!"
Write-Host $Error
Return $False
} #end else
IF ($LogPath) {
#After LogPath determination - try to log the string
Try {
Write-Host "$LogLine"
Add-content $LogPath\$LogFile -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): $LogLine" -ErrorAction Stop
#Return $True
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot write to LogFile!"
Write-Host "DEBUG Info - Write-LogFile: Exiting, because of this Issue."
Write-Host $Error
EXIT
} #end catch
} #end if
ELSE {
Write-Host "DEBUG Info - Write-LogFile: Cannot write to LogFile!"
Write-Host "DEBUG Info - Write-LogFile: Exiting, because of this Issue."
Write-Host $Error
EXIT
} #end else
} #end function