#PowerShell 3.0 Script #This Script will analyse and complete MailStore MPR Files, based on the EML Files. #Please use the "_Settings.ini"-File for configurations. #Digital Data #Ludwig-Rinn-Strasse 16 #35452 Heuchelheim #Tel.: 0641 / 202360 #E-Mail: info@didalog.de #Version Number: 1.0.0.0 #Version Date: 30.12.2016 #Requires –Version 3.0 #-----------------------------------------------------------------------------------------------------# ######################################## check for arguments ########################################## #-----------------------------------------------------------------------------------------------------# #-----------------------------------------------------------------------------------------------------# ###################################### add additional assemblys ####################################### #-----------------------------------------------------------------------------------------------------# Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop Add-Type -AssemblyName PresentationCore -ErrorAction Stop Add-Type -AssemblyName PresentationFramework -ErrorAction Stop #-----------------------------------------------------------------------------------------------------# ############################################ set variables ############################################ #-----------------------------------------------------------------------------------------------------# Set-Variable -Scope Global -Name ScriptName -Value (($MyInvocation.MyCommand.Name) -split "\.")[0].ToString() Set-Variable -Scope Global -Name ScriptPath -Value (Split-Path ($MyInvocation.MyCommand.Path)) Set-Variable -Scope Global -Name ConfigFile -Value (Get-ChildItem -Path "$ScriptPath" -Recurse -Filter "$ScriptName`_Settings.ini" -File -Force).FullName Set-Variable -Scope Global -Name ConfigValues -Value $NULL Set-Variable -Scope Global -Name Timestamp1 -Value $(Get-Date -Format 'ddMMyyyy') Set-Variable -Scope Global -Name Timestamp2 -Value $(Get-Date -Format 'ddMMyyyy_HHmmss') Set-Variable -Scope Global -Name Timestamp3 -Value $(Get-Date -Format 'ddMMyyyy_HHmmssffff') Set-Variable -Scope Global -Name Timestamp4 -Value $(Get-Date -Format 'yyyyMMdd HH:mm:ss.fff') Set-Variable -Scope Global -Name Item -Value $NULL Set-Variable -Scope Global -Name Items -Value $NULL Set-Variable -Scope Global -Name VersionSeperator -Value "~" Set-Variable -Scope Global -Name Counter1 -Value 0 Set-Variable -Scope Global -Name LogFile -Value "$ScriptName`_$Timestamp2.log" Set-Variable -Scope Global -Name LogFileKeepTime -Value 60 Set-Variable -Scope Global -Name LogPath -Value $NULL Set-Variable -Scope Global -Name LogPaths -Value $NULL Set-Variable -Scope Global -Name FileDelayAge -Value 5 Set-Variable -Scope Global -Name FileTest -Value $NULL Set-Variable -Scope Global -Name FileTest2 -Value $NULL Set-Variable -Scope Global -Name FileTest3 -Value $NULL Set-Variable -Scope Global -Name PathPath -Value $NULL Set-Variable -Scope Global -Name PathPath2 -Value $NULL Set-Variable -Scope Global -Name PathPaths -Value $NULL Set-Variable -Scope Global -Name Module -Value $NULL Set-Variable -Scope Global -Name Modules -Value ("Read-ConfigFile","Write-LogFile","Remove-Item-withLogging","Test-Path-withLogging","Load-EMLFile-withLogging","MoveOrCopy-Item-withLogging","Test-FileState-withLogging") Set-Variable -Scope Global -Name ModuleOverrideSourcePath -Value $NULL Set-Variable -Scope Global -Name ModuleDefaultSourcePath -Value $NULL Set-Variable -Scope Global -Name ModuleHKLMRegistryPath -Value "HKLM:\SOFTWARE\Digital Data\Modules" Set-Variable -Scope Global -Name ModuleHKCURegistryPath -Value "HKCU:\SOFTWARE\Digital Data\Modules" Set-Variable -Scope Global -Name SMTPDomain -Value $NULL Set-Variable -Scope Global -Name SMTPDomains -Value $NULL Set-Variable -Scope Global -Name SMTPDomainsTEMP -Value $NULL Set-Variable -Scope Global -Name SMTPAddress -Value $NULL Set-Variable -Scope Global -Name POPAddresses -Value $NULL Set-Variable -Scope Global -Name POPAddressTO -Value $NULL Set-Variable -Scope Global -Name POPAddressesTO -Value $NULL Set-Variable -Scope Global -Name POPAddressCC -Value $NULL Set-Variable -Scope Global -Name POPAddressesCC -Value $NULL Set-Variable -Scope Global -Name POPAddressBCC -Value $NULL Set-Variable -Scope Global -Name POPAddressesBCC -Value $NULL Set-Variable -Scope Global -Name POPAddressTEMP -Value $NULL Set-Variable -Scope Global -Name POPAddressesTEMP -Value $NULL Set-Variable -Scope Global -Name SourcePath -Value $NULL Set-Variable -Scope Global -Name TargetPath -Value $NULL Set-Variable -Scope Global -Name ErrorPath -Value $NULL Set-Variable -Scope Global -Name EMLFile -Value $NULL Set-Variable -Scope Global -Name EMLFileBaseName -Value $NULL Set-Variable -Scope Global -Name EMLFileExtension -Value "eml" Set-Variable -Scope Global -Name EMLFileContent -Value $NULL Set-Variable -Scope Global -Name EMLObject -Value $NULL Set-Variable -Scope Global -Name MPRFile -Value $NULL Set-Variable -Scope Global -Name MPRFileBaseName -Value $NULL Set-Variable -Scope Global -Name MPRFileExtension -Value "mpr" Set-Variable -Scope Global -Name MPRFileContent -Value $NULL Set-Variable -Scope Global -Name MPRFileContentPOPValue -Value $NULL Set-Variable -Scope Global -Name MPRFileContentPOPIndex -Value $NULL Set-Variable -Scope Global -Name MPRFileContentSMTPValue -Value $NULL Set-Variable -Scope Global -Name MPRFileContentSMTPIndex -Value $NULL Set-Variable -Scope Global -Name TargetPathErrorFileDelayAge -Value 7 #-----------------------------------------------------------------------------------------------------# ############################################ set functions ############################################ #-----------------------------------------------------------------------------------------------------# Function Load-PowerShellModule { <# .SYNOPSIS Function will load external - additional - PowerShell Modules into current PSSession. .DESCRIPTION By working with Modules, this Function is necessary to load external Modul Functions into the current PowerShell Session. In a productive Enviroment it is recommanded to let this Function set the Registry Key in HKLM for the ModuleSourcePath. In develepment and Test Enviroment it is possible, to work with distributed Folders with different Modules. Therefor the Parameter "ModuleOverrideSourcePath" and the preset Variable "ModuleDefaultSourcePath" are made for. After a successful Import of a Module, Function will Return $True, otherwise a $False. .REQUIREMENT General PowerShell V3 .REQUIREMENT Assembly System.Windows.Forms, PresentationCore, PresentationFramework .REQUIREMENT Variables ModuleOverrideSourcePath, ModuleName, Path, Paths, PathTest, FileTest, Result .REQUIREMENT Variables preSet ScriptName, ScriptPath, ModuleDefaultSourcePath, Counter .REQUIREMENT Functions .VERSION 1.0.0.0 / 11.09.2016 .PARAMETER ModuleName Give the Module Name, you want to load into the current PSSession (without File-Extension). .PARAMETER ModuleOverrideSourcePath Optional Parameter. By giving the ModuleOverrideSourcePath, Function will not check other Paths for the Function you want to load. .PARAMETER ModuleFileExtension Optional Parameter. Give the Module File-Extension (regular: "psm1") without a dot ("."), this is just for the checking routine, not the Import itself.')] .PARAMETER Force Optional Parameter. By using the Force Parameter, Module will be unload and reload. .EXAMPLE Load-PowerShellModule -ModuleName Write-LogFile -ModuleFileExtension psm1 .EXAMPLE Load-PowerShellModule -ModuleName Write-LogFile -Force .EXAMPLE Load-PowerShellModule -ModuleName Write-LogFile -ModuleFileExtension psm1 -ModuleOverrideSourcePath D:\ScriptFiles\Modules #> [cmdletbinding()] Param ( [Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$True,HelpMessage='Give the ModuleName, you want to load into the current PSSession (without File-Extension)')] [ValidateNotNullOrEmpty()] [String]$ModuleName, [Parameter(mandatory=$False,HelpMessage='Optional Parameter. By giving the ModuleOverrideSourcePath, Function will not check other Paths for the Function you want to load.')] [ValidateNotNullOrEmpty()] [String]$ModuleOverrideSourcePath, [Parameter(mandatory=$False,HelpMessage='Optional Parameter. Give the Module File-Extension (regular: "psm1") without a dot ("."), this is just for the checking routine, not the Import itself.')] [ValidateNotNullOrEmpty()] [String]$ModuleFileExtension = "psm1", [Parameter(mandatory=$False,HelpMessage='Optional Parameter. By using the Force Parameter, Module will be unload and reload.')] [Switch]$Force ) #end param Process { #Clear Error Variable $error.clear() #If FileExtension was given, remove it! Because otherwise "Import-Module" Function will have trouble importing. $ModuleName = $ModuleName.Replace(".$ModuleFileExtension","") Write-Host "DEBUG Info - Load-PowerShellModule: You want to load Module $ModuleName" #Try this if $ModuleOverrideSourcePath was given by calling the function IF ((([String]::IsNullOrWhiteSpace($ModuleOverrideSourcePath)) -ne $true) -and (([String]::IsNullOrEmpty($ModuleOverrideSourcePath)) -ne $true)) { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Function has been called with 'ModuleOverrideSourcePath' Parameter input!" Write-Host "DEBUG Info - Load-PowerShellModule: Testing for existence: $ModuleOverrideSourcePath\$ModuleName.$ModuleFileExtension" $PathTest = Test-Path -Path "$ModuleOverrideSourcePath\$ModuleName.$ModuleFileExtension" -PathType Leaf IF ($PathTest -eq $true) { Write-Host "DEBUG Info - Load-PowerShellModule: $ModuleOverrideSourcePath and ModuleName seems to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Trying to import Module: $ModuleName.$ModuleFileExtension" Try { $Result = Import-Module $ModuleOverrideSourcePath\$ModuleName -Verbose -DisableNameChecking -Scope Global -Force:$Force -PassThru -ErrorVariable Error -ErrorAction SilentlyContinue IF ("$Result" -eq "$ModuleName") { Write-Host "DEBUG Info - Load-PowerShellModule: Successfully loaded Module: $ModuleName.$ModuleFileExtension" Return $True } #end if ELSE { Write-Error "DEBUG Info - Load-PowerShellModule: Unsuccessfully loaded Module: $ModuleName.$ModuleFileExtension" Return $False } #end else } #end try Catch { Write-Host "DEBUG Info - Load-PowerShellModule: Error while importing the Module:" Write-Host "DEBUG Info - Load-PowerShellModule: $ModuleName" Write-Host $Error Return $False } #end catch } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: ModuleOverrideSourcePath and/or ModuleName seems not to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Cannot load Module, please check your input!" Return $False } #end else } #end if #If $ModuleOverrideSourcePath was not given, try to find a matching folder ELSE { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Function has been called without 'ModuleOverrideSourcePath' Parameter input!" Write-Host "DEBUG Info - Load-PowerShellModule: Trying to find Module Files on some Places of this Computer." #Set dynamic Array for locations Modul Path could be, even for some testing. #The first value of the array is just a dummy and will never be used -but keep it for the array value starting with 0! [System.Collections.ArrayList]$Paths = @() Write-Host "" $Paths.Add("$env:systemroot\") | Out-Null IF (([String]::IsNullOrEmpty($ModuleDefaultSourcePath)) -or ([String]::IsNullOrWhiteSpace($ModuleDefaultSourcePath))) { Write-Host "DEBUG Info - Load-PowerShellModule: ModuleDefaultSourcePath was not set! That could be a normal behavior in productive enviroment!" } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (1): $ModuleDefaultSourcePath" -ErrorAction SilentlyContinue $Paths.Add("$ModuleDefaultSourcePath") | Out-Null } #end else IF ([String]::IsNullOrEmpty($ScriptPath) -or ([String]::IsNullOrWhiteSpace($ScriptPath))) { Write-Host "DEBUG Info - Load-PowerShellModule: ScriptPath is invalid! That is terrifying! How could that be???" } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (2): $ScriptPath" -ErrorAction SilentlyContinue $Paths.Add("$ScriptPath") | Out-Null Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (3): $($ScriptPath+"\Module")" -ErrorAction SilentlyContinue $Paths.Add("$($ScriptPath+"\Module")") | Out-Null Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (4): $($ScriptPath+"\Modules")" -ErrorAction SilentlyContinue $Paths.Add("$($ScriptPath+"\Modules")") | Out-Null } #end else IF (([String]::IsNullOrEmpty((Get-Item $ScriptPath).Parent.FullName)) -or ([String]::IsNullOrWhiteSpace((Get-Item $ScriptPath).Parent.FullName))) { Write-Host "DEBUG Info - Load-PowerShellModule: ScriptPath has no Parent Folders!" } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (5): $((Get-Item $ScriptPath).Parent.FullName)" -ErrorAction SilentlyContinue $Paths.Add("$((Get-Item $ScriptPath).Parent.FullName)") | Out-Null Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (6): $(((Get-Item $ScriptPath).Parent.FullName)+"\Module")" -ErrorAction SilentlyContinue $Paths.Add("$(((Get-Item $ScriptPath).Parent.FullName)+"\Module")") | Out-Null Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (7): $(((Get-Item $ScriptPath).Parent.FullName)+"\Modules")" -ErrorAction SilentlyContinue $Paths.Add("$(((Get-Item $ScriptPath).Parent.FullName)+"\Modules")") | Out-Null } #end else IF (([String]::IsNullOrEmpty($((Get-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath))) -or ([String]::IsNullOrWhiteSpace($((Get-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)))) { Write-Host "DEBUG Info - Load-PowerShellModule: ModuleSourcePath was not set to Windows Registry (HKLM)!" } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (8): $((Get-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)" -ErrorAction SilentlyContinue $Paths.Add("$((Get-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)") | Out-Null } #end else IF (([String]::IsNullOrEmpty($((Get-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath))) -or ([String]::IsNullOrWhiteSpace($((Get-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)))) { Write-Host "DEBUG Info - Load-PowerShellModule: ModuleSourcePath was not set to Windows Registry (HKCU)!" } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Possible Path (8): $((Get-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)" -ErrorAction SilentlyContinue $Paths.Add("$((Get-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -ErrorAction SilentlyContinue).ModuleSourcePath)") | Out-Null } #end else [Int]$Counter = 0 [String]$ModuleSourcePath = $Null #Loop for multiple Pathtests - for each Path, where psm1 files could be DO { $Counter++ Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Testing mutiple Paths ( $Counter of"($($Paths.Count)-1)") for existence, now testing:" Write-Host "DEBUG Info - Load-PowerShellModule: $($Paths[$Counter])" IF ($($Paths[$Counter]) -gt $Null) { $PathTest = Test-Path $($Paths[$Counter]) -ErrorAction SilentlyContinue IF ($PathTest -eq $true) { Write-Host "DEBUG Info - Load-PowerShellModule: Yes, Path seems to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Lets check, if there are any Module Files, in it." $FileTest = Get-ChildItem -Path $($Paths[$Counter]) -Filter *.$ModuleFileExtension IF ($($FileTest.count) -gt 0) { Write-Host "DEBUG Info - Load-PowerShellModule: Found $($FileTest.count) psm1 Module Files in Path!" Set-Variable -Name ModuleSourcePath -Value $($Paths[$Counter]) -Scope local } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Found no $ModuleFileExtension Module Files in Path!" } #end else } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: No, Path seems not to exist." } #end else } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Path seems to be invalid!" } #end else } #end do UNTIL ($Counter -ge ($($Paths.Count)-1) -or ($ModuleSourcePath -eq $($Paths[$Counter]))) IF ($ModuleSourcePath -eq $($Paths[$Counter])) { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Trying to import Module: $ModuleName.$ModuleFileExtension" Try { $Result = Import-Module $ModuleSourcePath\$ModuleName -Verbose -DisableNameChecking -Scope Global -Force:$Force -PassThru -ErrorVariable Error -ErrorAction SilentlyContinue IF ("$Result" -eq "$ModuleName") { Write-Host "DEBUG Info - Load-PowerShellModule: Successfully loaded Module: $ModuleName.$ModuleFileExtension" Return $true } #end if ELSE { Write-Error "DEBUG Info - Load-PowerShellModule: Unsuccessfully loaded Module: $ModuleName.$ModuleFileExtension" Return $False } #end else } #end try Catch { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Loading Module: $ModuleName went wrong." Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this error!" Write-Host $Error Return $False exit } #end catch } #end if ELSE { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Cant locate Module Files automaticlly!" Write-Host "DEBUG Info - Load-PowerShellModule: Please select Folder in Dialog." #Prepare Folder Browser Dialog, to choose the Directory with the .psm1 Files. $FolderBrowserDialog = New-Object System.Windows.Forms.FolderBrowserDialog $FolderBrowserDialog.Rootfolder = "Desktop" $FolderBrowserDialog.Description = "Please, choose the Folder, where the Module ""$ModuleName.$ModuleFileExtension"" is stored." $FolderBrowserDialog.SelectedPath = "$ScriptPath" $FolderBrowserDialog.ShowNewFolderButton = $true DO { #Now show the Folder Browser, if neccessary in a loop $FolderBrowserDialogShow = $FolderBrowserDialog.ShowDialog() #By pressing the OK Button.. If ($FolderBrowserDialogShow -eq "OK") { #Save selected folder path in the variable $ModuleSourcePath = ($FolderBrowserDialog.SelectedPath) Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: You choose: $ModuleSourcePath" Write-Host "DEBUG Info - Load-PowerShellModule: ...testing, if Module ""$ModuleName.$ModuleFileExtension"" can be found there." $PathTest = (Test-Path $ModuleSourcePath\$ModuleName.$ModuleFileExtension) IF ($PathTest -eq $True) { Write-Host "DEBUG Info - Load-PowerShellModule: Module seems to exist, in the selected Folder." Write-Host "DEBUG Info - Load-PowerShellModule: Now trying to load Module: $ModuleName.$ModuleFileExtension" Try { $Result = Import-Module $ModuleSourcePath\$ModuleName -Verbose -DisableNameChecking -Scope Global -Force:$Force -PassThru -ErrorVariable Error -ErrorAction SilentlyContinue IF ("$Result" -eq "$ModuleName") { $MessageBoxBody = "Module: $ModuleName.$ModuleFileExtension - successsfully loaded into current PSSession!" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Information" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) | Out-Null } #end if ELSE { $MessageBoxBody = "Module: $ModuleName.$ModuleFileExtension - cannot load into current PSSession!" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Warning" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) | Out-Null } #end else } #end try Catch { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Loading Module: $ModuleName.$ModuleFileExtension went wrong." Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this error!" Write-Host $Error exit } #end catch } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Module seems not to exist, in the selected Folder." Write-Host "DEBUG Info - Load-PowerShellModule: Please, select another one! ...this Time the right!" $MessageBoxBody = "Module seems not to exist, in the selected Folder! Please, select another one!" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Warning" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) | Out-Null } #end else } #end if #If you didnt pressed the OK Button.. Else { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Operation cancelled by user." Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this!" exit } #end else } #end do #Variable "$?" is $true when last operation was ok UNTIL ((($PathTest -eq $True) -and ($? -eq $true)) -or ($FolderBrowserDialogShow -eq "Cancel")) IF ($ModuleSourcePath -gt $Null) { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Should ModuleSourcePath written to Windows Registry?" $MessageBoxBody = "Would you like to save the ModulePath to the Windows Registry?" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "YesNo" $MessageBoxIcon = "Question" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) IF ($MessageBox -eq 'Yes') { $PathTest = (Test-Path -Path "$ModuleHKLMRegistryPath") $MessageBox = $NULL IF ($PathTest -eq $False) { Write-Host "DEBUG Info - Load-PowerShellModule: Registry Key seems not to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Trying to write ModuleSourcepath to HKLM." Try { New-Item -Path "$ModuleHKLMRegistryPath" -Force -ErrorVariable Error -ErrorAction Stop | Out-Null New-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -ErrorVariable Error -ErrorAction Stop | Out-Null $env:PSModulePath = $env:PSModulePath + ";" + "$ModuleSourcePath" } #end try Catch { Write-Host $Error $MessageBoxBody = "Could not save ModuleSourcePath to Windows Registry! Check your access rights! To bypass this issue you can write the ModuleSourcePath to User Registry (HKCU). Would you?" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "YesNo" $MessageBoxIcon = "Question" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) } #end catch } #end if ELSEIF ($PathTest -eq $True) { Write-Host "DEBUG Info - Load-PowerShellModule: Registry Key seems to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Trying to write ModuleSourcepath to HKLM." Try { Set-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -ErrorVariable Error -ErrorAction Stop | Out-Null } #end try Catch { Write-Host $Error $MessageBoxBody = "Could not save ModuleSourcePath to Windows Registry! Check your access rights! To Bypass Error: Write ModuleSource Path to User Registry (HKCU)?" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "YesNo" $MessageBoxIcon = "Question" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) } #end catch } #end elseif ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Something went wrong, by getting the ModuleSourcePath!" Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this!" exit } #end else #Block for trying to write the ModuleSourcePath to the User Registry, if System Registry failed. IF ($MessageBox -eq 'Yes') { $PathTest = (Test-Path -Path "$ModuleHKCURegistryPath") $MessageBox = $NULL IF ($PathTest -eq $False) { Write-Host "DEBUG Info - Load-PowerShellModule: Registry Key seems not to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Trying to write ModuleSourcepath to HKCU." Try { New-Item -Path "$ModuleHKCURegistryPath" -Force -ErrorVariable Error -ErrorAction Stop | Out-Null New-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -ErrorAction Stop | Out-Null $env:PSModulePath = $env:PSModulePath + ";" + "$ModuleSourcePath" } #end try Catch { Write-Host $Error $MessageBoxBody = "Could not save ModuleSourcePath to Windows Registry! Not even to User Registry! Check your access rights! Exiting now.." $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Warning" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) exit } #end catch } #end if ELSEIF ($PathTest -eq $True) { Write-Host "DEBUG Info - Load-PowerShellModule: Registry Key seems to exist." Write-Host "DEBUG Info - Load-PowerShellModule: Trying to write ModuleSourcepath to HKCU." Try { Set-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -ErrorVariable Error -ErrorAction Stop | Out-Null } #end try Catch { Write-Host $Error $MessageBoxBody = "Could not save ModuleSourcePath to Windows Registry! Not even to User Registry! Check your access rights! Exiting now.." $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Warning" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) exit } #end catch } #end elseif ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Something went wrong, by getting the ModuleSourcePath!" Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this!" exit } #end else } #end if } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: You choose, not to save the ModuleSourcePath to the Windows Registry!" $MessageBoxBody = "You choose, not to save the ModuleSourcePath to the Windows Registry!" $MessageBoxTitle = "ScriptName: $ScriptName - Module/Section: Load-PowerShellModule" $MessageBoxButtonType = "OK" $MessageBoxIcon = "Warning" $MessageBox = [Windows.Forms.MessageBox]::Show($MessageBoxBody,$MessageBoxTitle,$MessageBoxButtonType,$MessageBoxIcon) } #end else } #end if ELSE { Write-Host "DEBUG Info - Load-PowerShellModule: Something went wrong, by getting the ModuleSourcePath!" Write-Host "DEBUG Info - Load-PowerShellModule: Exiting Script, because of this!" exit } #end else } #end else } #end else } #end process } #end function #-----------------------------------------------------------------------------------------------------# ########################################### preparing part ############################################ #-----------------------------------------------------------------------------------------------------# #Clear Console Content Clear-Host #Load external Modules - use Force ( -Force) Parameter, to reload in every run FOREACH ($Module in $Modules) { $Result = Load-PowerShellModule -ModuleName $Module -Force IF ($Result -eq $False) { Write-Host "DEBUG Info: Module: $Module was not succesful been loaded!" Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!" Write-Host "DEBUG Info: Exiting, because of this Issue." Write-Host $Error EXIT } #end if } #end foreach #Read ConfigFile, to get all values Set-Variable -Scope Global -Name ConfigValues -Value (Read-ConfigFile -ConfigFile $ConfigFile) -Force #Allocate Variable Values, depending on the read ConfigFile Set-Variable -Scope Global -Name LogPaths -Value (Read-ConfigFile -ConfigLabel LogPath) -Force Set-Variable -Scope Global -Name LogFileKeepTime -Value (Read-ConfigFile -ConfigLabel LogFileKeepTime) -Force Set-Variable -Scope Global -Name VersionSeperator -Value (Read-ConfigFile -ConfigLabel VersionSeperator) -Force Set-Variable -Scope Global -Name FileDelayAge -Value (Read-ConfigFile -ConfigLabel FileDelayAge) -Force Set-Variable -Scope Global -Name SMTPDomains -Value (Read-ConfigFile -ConfigLabel SMTPDomains) -Force Set-Variable -Scope Global -Name SourcePath -Value (Read-ConfigFile -ConfigLabel SourcePath) -Force Set-Variable -Scope Global -Name TargetPath -Value (Read-ConfigFile -ConfigLabel TargetPath) -Force Set-Variable -Scope Global -Name ErrorPath -Value (Read-ConfigFile -ConfigLabel ErrorPath) -Force Set-Variable -Scope Global -Name EMLFileExtension -Value (Read-ConfigFile -ConfigLabel EMLFileExtension) -Force Set-Variable -Scope Global -Name MPRFileExtension -Value (Read-ConfigFile -ConfigLabel MPRFileExtension) -Force Set-Variable -Scope Global -Name TargetPathErrorFileDelayAge -Value (Read-ConfigFile -ConfigLabel TargetPathErrorFileDelayAge) -Force #Rebuild the Array, to remove possible Blanks [Array]$SMTPDomains = $SMTPDomains -split "," [Array]$SMTPDomains = $SMTPDomains -split ";" [System.Collections.ArrayList]$SMTPDomainsTEMP = @() FOREACH ($SMTPDomain in $SMTPDomains) { $SMTPDomain = ($SMTPDomain.TrimStart()) $SMTPDomain = ($SMTPDomain.TrimEnd()) $SMTPDomainsTEMP.Add("$SMTPDomain") } #end foreach [Array]$SMTPDomains = $NULL [Array]$SMTPDomains = $SMTPDomainsTEMP #-----------------------------------------------------------------------------------------------------# ############################################# main part ############################################### #-----------------------------------------------------------------------------------------------------# Write-Logfile -LogLine " " Write-Logfile -LogLine "********************************************************************************" Write-Logfile -LogLine "Program Startup: $ScriptName on $env:COMPUTERNAME," Write-Logfile -LogLine "from Account $env:USERDOMAIN\$env:USERNAME." Write-Logfile -LogLine "********************************************************************************" $PathTest = Test-Path-withLogging -Path $SourcePath -Action "ignore" $PathTest2 = Test-Path-withLogging -Path $TargetPath IF (($PathTest -eq $True) -and ($PathTest2 -eq $True)) { #Check for files which have to be processed IF (($FileDelayAge) -and ($FileDelayAge -gt 0)) { Write-Host "DEBUG Info: FileDelayAge set to $FileDelayAge" $Items = (Get-ChildItem -Path $SourcePath -Filter "*.$EMLFileExtension" | where {$_.lastwritetime -lt $((Get-Date).AddMinutes(-$FileDelayAge)) -and -not $_.psiscontainer}) } #end if ELSE { Write-Host "DEBUG Info: FileDelayAge set to $FileDelayAge" $Items = (Get-ChildItem -Path $SourcePath -Filter "*.$EMLFileExtension") } #end else #If there are files, go on to process them IF ($Items){ FOREACH ($Item in $Items) { $EMLFile = $($Item.FullName) $EMLFileBaseName = ([System.IO.Path]::GetFileName($($Item.FullName))) $MPRFile = ([System.IO.Path]::GetDirectoryName($($Item.FullName)).ToString() + "\" + [System.IO.Path]::GetFileNameWithoutExtension($($Item.FullName)) + "." + $MPRFileExtension) $MPRFileBaseName = ([System.IO.Path]::GetFileNameWithoutExtension($($Item.FullName)) + "." + $MPRFileExtension) Write-LogFile -LogLine " " Write-Logfile -LogLine "--------------------------------------------------------------------------------" Write-LogFile -LogLine "Checking, if there is a MailStore Proxy File," Write-LogFile -LogLine "for E-Mail $($Item.FullName)." Write-Logfile -LogLine "--------------------------------------------------------------------------------" Write-LogFile -LogLine "Current Source EML File: $EMLFile" Write-LogFile -LogLine "Current Target MPR File: $MPRFile" $FileTest = Test-Path -Path $MPRFile -PathType Leaf $FileTest2 = Test-Path -Path $TargetPath\$MPRFileBaseName -PathType Leaf $FileTest3 = Test-Path -Path $TargetPath\$EMLFileBaseName -PathType Leaf IF (($FileTest -eq $True) -and (($FileTest2 -eq $False) -or ($FileTest3 -eq $False))) { Write-LogFile -LogLine "Source MPR File exists!" #Checking if Files are Read and writeable for the next Steps $FileTest2 = Test-FileState-withLogging -SourceFile "$SourcePath\$MPRFileBaseName" -Action writetest $FileTest3 = Test-FileState-withLogging -SourceFile "$SourcePath\$EMLFileBaseName" -Action writetest IF (($FileTest2 -eq "writeable") -and ($FileTest3 -eq "writeable")) { Try { Write-LogFile -LogLine "Reading MPRFileContent..." [System.Collections.ArrayList]$MPRFileContent = @() $MPRFileContent = (Get-Content $MPRFile -ErrorAction Stop) [System.Collections.ArrayList]$MPRFileContent = @($MPRFileContent) } #end try Catch { Write-LogFile -LogLine "Error by reading MPRFileContent" } #end catch #If POP Activity found in the File IF ($MPRFileContent -match 'POP3-Recipient:') { #Identify row/line which include the POP marker [String]$MPRFileContentPOPValue = $MPRFileContent | Where({$_ -match 'POP3-Recipient:'}) [int]$MPRFileContentPOPIndex = $MPRFileContent.IndexOf($MPRFileContentPOPValue) Write-LogFile -LogLine "Found POP transaction in file (on line: $MPRFileContentPOPIndex)." IF ($MPRFileContentPOPValue -match $SMTPDomains) { Write-LogFile -LogLine "Found valid POP transaction in file:" Write-LogFile -LogLine "$MPRFileContentSMTPValue" Write-LogFile -LogLine "There is nothing to do, just moving EML and MPR files" Try { MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $TargetPath -Action move MoveOrCopy-Item-withLogging -SourceFile $MPRFile -DestinationPath $TargetPath -Action move } #end try Catch { Write-LogFile -LogLine "Error, could not move files:" Write-LogFile -LogLine $EMLFile Write-LogFile -LogLine $MPRFile } #end catch } #end if ELSEIF ($MPRFileContentPOPValue -notmatch $SMTPDomains) { #Prepare dynamic Array for temp E-Mail adresses [System.Collections.ArrayList]$POPAddressesTEMP = @() #Retrieve EML Object $EMLObject = Load-EMLFile-withLogging -EMLFileName $EMLFile #Read EML Mail TO Attributes to get POP Receiver Adresses IF (($EMLObject.TO).count -gt 0) { Write-LogFile -LogLine "Found $($POPAddressesBCC.Count) E-Mail Adresses in the BCC Attribut." [Array]$POPAddressesTO = ($EMLObject.TO) [Array]$POPAddressesTO = ($POPAddressesTO -Split ',') [Array]$POPAddressesTO = ($POPAddressesTO -Split ';') [Array]$POPAddressesTO = ($POPAddressesTO -Split ' ') FOREACH ($POPAddressTO in $POPAddressesTO) { $POPAddressTO = ($POPAddressTO | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value }) #Fill array, if Value is greater than $NULL IF ($POPAddressTO) { Write-Host "DEBUG Info: Valid POPAddressTO: $POPAddressTO" $POPAddressTO = ($POPAddressTO -Replace('\<|\>|\(|\)|\[|\]|\"|\s\,\;\:\=\\','')) $POPAddressTO = ($POPAddressTO -Replace("'","")) $POPAddressTO = ($POPAddressTO.TrimStart()) $POPAddressTO = ($POPAddressTO.TrimEnd()) $POPAddressTO = ($POPAddressTO.ToLower()) [Array]$POPAddressesTEMP = ($POPAddressesTEMP + $POPAddressTO) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Sort-Object) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Select -Unique) } #end if ELSE { Write-Host "DEBUG Info: Invalid POPAddressTO!" } #end else } #end foreach } #end if ELSE { Write-LogFile -LogLine "There are no E-Mail addresses in the TO Attribut of this Mail!" } #end else #Read EML Mail CC Attributes to get POP Receiver Adresses IF (($EMLObject.CC).count -gt 0) { Write-LogFile -LogLine "Found $($POPAddressesCC.Count) E-Mail Adresses in the CC Attribut." [Array]$POPAddressesCC = ($EMLObject.CC) [Array]$POPAddressesCC = ($POPAddressesCC -Split ',') [Array]$POPAddressesCC = ($POPAddressesCC -Split ';') [Array]$POPAddressesCC = ($POPAddressesCC -Split ' ') FOREACH ($POPAddressCC in $POPAddressesCC) { $POPAddressCC = ($POPAddressCC | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value }) #Fill array, if Value is greater than $NULL IF ($POPAddressCC) { Write-Host "DEBUG Info: Valid POPAddressCC: $POPAddressCC" $POPAddressCC = ($POPAddressCC -Replace('\<|\>|\(|\)|\[|\]|\"|\s\,\;\:\=\\','')) $POPAddressCC = ($POPAddressCC -Replace("'","")) $POPAddressCC = ($POPAddressCC.TrimStart()) $POPAddressCC = ($POPAddressCC.TrimEnd()) $POPAddressCC = ($POPAddressCC.ToLower()) [Array]$POPAddressesTEMP = ($POPAddressesTEMP + $POPAddressCC) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Sort-Object) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Select -Unique) } #end if ELSE { Write-Host "DEBUG Info: Invalid POPAddressCC!" } #end else } #end foreach } #end if ELSE { Write-LogFile -LogLine "There are no E-Mail addresses in the CC Attribut of this Mail!" } #end else #Read EML Mail BCC Attributes to get POP Receiver Adresses IF (($EMLObject.BCC).count -gt 0) { Write-LogFile -LogLine "Found $($POPAddressesBCC.Count) E-Mail Adresses in the BCC Attribut." [Array]$POPAddressesBCC = ($EMLObject.BCC) [Array]$POPAddressesBCC = ($POPAddressesBCC -Split ',') [Array]$POPAddressesBCC = ($POPAddressesBCC -Split ';') [Array]$POPAddressesBCC = ($POPAddressesBCC -Split ' ') FOREACH ($POPAddressBCC in $POPAddressesBCC) { $POPAddressBCC = ($POPAddressBCC | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value }) #Fill array, if Value is greater than $NULL IF ($POPAddressBCC) { Write-Host "DEBUG Info: Valid POPAddressCC: $POPAddressCC" $POPAddressBCC = ($POPAddressBCC -Replace('\<|\>|\(|\)|\[|\]|\"|\s\,\;\:\=\\','')) $POPAddressBCC = ($POPAddressBCC -Replace("'","")) $POPAddressBCC = ($POPAddressBCC.TrimStart()) $POPAddressBCC = ($POPAddressBCC.TrimEnd()) $POPAddressBCC = ($POPAddressBCC.ToLower()) [Array]$POPAddressesTEMP = ($POPAddressesTEMP + $POPAddressBCC) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Sort-Object) [Array]$POPAddressesTEMP = ($POPAddressesTEMP | Select -Unique) } #end if ELSE { Write-Host "DEBUG Info: Invalid POPAddressBCC!" } #end else } #end foreach } #end if ELSE { Write-LogFile -LogLine "There are no E-Mail addresses in the BCC Attribut of this Mail!" } #end else #Prepare final dynamic Array for E-Mail addresses [System.Collections.ArrayList]$POPAddresses = @() IF ($POPAddressesTEMP.count -lt 1) { Write-LogFile -LogLine "Summary: Found none valid E-Mail adress(es) for this Mail, via EML Object." Write-LogFile -LogLine "Now trying via EML Sourcecode!" Try { $EMLFileContent = Get-Content $EMLFile [String]$POPAddressesTEMP.Add(($EMLFileContent | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value })) [Array]$POPAddressesTEMP = $POPAddressesTEMP -split " " } #end try Catch { Write-LogFile -LogLine "Cannot get Sourcecode from EMLFile: $EMLFile" } #end catch IF ($POPAddressesTEMP.Count -gt 1 ) { Write-LogFile -LogLine "Found $($POPAddressesTEMP.Count) E-Mail addresses in the EML Sourcecode." FOREACH ($POPAddressTEMP in $POPAddressesTEMP) { $POPAddressTEMP = ($POPAddressTEMP -Replace('<','')) $POPAddressTEMP = ($POPAddressTEMP -Replace('>','')) $POPAddressTEMP = ($POPAddressTEMP -Replace('"','')) $POPAddressTEMP = ($POPAddressTEMP -Replace("'","")) $POPAddressTEMP = ($POPAddressTEMP.TrimStart()) $POPAddressTEMP = ($POPAddressTEMP.TrimEnd()) $POPAddressTEMP = ($POPAddressTEMP.ToLower()) $POPAddresses.Add(('POP3-Recipient: '+ $POPAddressTEMP | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value })) $POPAddresses.Remove($NULL) } #end foreach #Filter and remove duplicates [Array]$POPAddresses = $POPAddresses | Sort-Object [Array]$POPAddresses = $POPAddresses | Select -Unique } #end if ELSEIF ($POPAddressesTEMP.Count -eq 1 ) { Write-LogFile -LogLine "Found exacly one E-Mail address in the EML Sourcecode." } #end elseif } #end if ELSEIF ($POPAddressesTEMP.count -gt 0) { Write-LogFile -LogLine "Summary: Found $($POPAddressesTEMP.Count) valid E-Mail adress(es) for this Mail, via EML Object." [Array]$POPAddressesTEMP = $POPAddressesTEMP | Sort-Object [Array]$POPAddressesTEMP = $POPAddressesTEMP | Select -Unique FOREACH ($POPAddressTEMP in $POPAddressesTEMP) { IF ($POPAddressTEMP) { $POPAddressTEMP = 'POP3-Recipient: '+$POPAddressTEMP $POPAddresses.Add($POPAddressTEMP) } #end if } #end foreach } #end elseif #Replace and add new values to the array $MPRFileContent.RemoveAt($MPRFileContentPOPIndex) $MPRFileContent.InsertRange($MPRFileContentPOPIndex, $POPAddresses) Try { Write-LogFile -LogLine " " Write-LogFile -LogLine "Creating new and corrected MPR File." New-Item -ItemType "file" $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop Clear-Content $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop $MPRFileContent | Set-Content $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $TargetPath -Action move Write-LogFile -LogLine "Removing old MPR File." Remove-Item -Path $MPRFile -Force -ErrorAction Stop } #end try Catch { Write-LogFile -LogLine "Error, could not write to file:" Write-LogFile -LogLine $MPRFile Write-LogFile -LogLine "Please check your access rights!" } #end catch } #end elseif ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "Ivalide MPR File!" Write-LogFile -LogLine "Moving to ErrorPath: $ErrorPath" Try { MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $ErrorPath -Action move MoveOrCopy-Item-withLogging -SourceFile $MPRFile -DestinationPath $ErrorPath -Action move } #end try Catch { Write-LogFile -LogLine "Error, could not move files:" Write-LogFile -LogLine $EMLFile Write-LogFile -LogLine $MPRFile } #end catch } #end else } #end if #If SMTP Activity found in the File ELSEIF ($MPRFileContent -match 'SMTP-Mail-From') { #Identify row/line which include the SMTP marker [String]$MPRFileContentSMTPValue = $MPRFileContent | Where({$_ -match 'SMTP-Mail-From'}) [int]$MPRFileContentSMTPIndex = $MPRFileContent.IndexOf($MPRFileContentSMTPValue) Write-LogFile -LogLine "Found SMTP transaction in file (on line: $MPRFileContentSMTPIndex)." IF ($MPRFileContentSMTPValue -match $SMTPDomains) { Write-LogFile -LogLine "Found valid SMTP transaction in File:" Write-LogFile -LogLine "$MPRFileContentSMTPValue" Write-LogFile -LogLine "There is nothing to do, just moving EML and MPR files" Try { MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $TargetPath -Action move MoveOrCopy-Item-withLogging -SourceFile $MPRFile -DestinationPath $TargetPath -Action move } #end try Catch { Write-LogFile -LogLine "Error, could not move files:" Write-LogFile -LogLine $EMLFile Write-LogFile -LogLine $MPRFile } #end catch } #end if ELSEIF ($MPRFileContentSMTPValue -notmatch $SMTPDomains) { Write-LogFile -LogLine "Found invalid SMTP transaction in file:" Write-LogFile -LogLine "$MPRFileContentSMTPValue" #Retrieve EML Object $EMLObject = Load-EMLFile-withLogging -EMLFileName $EMLFile #reset SMTPAddress $SMTPAddress = $NULL IF ($EMLObject.From -match $SMTPDomains) { Write-LogFile -LogLine "Found exacly one E-Mail address in the FROM Attribut." $SMTPAddress = ($EMLObject.From) $SMTPAddress = ($SMTPAddress | Select-String -Pattern $SMTPDomains -AllMatches | % { $_.Matches } | % { $_.Value }) $SMTPAddress = ($SMTPAddress -Replace('\<|\>|\(|\)|\[|\]|\"|\s\,\;\:\=\\','')) $SMTPAddress = ($SMTPAddress.TrimStart()) $SMTPAddress = ($SMTPAddress.TrimEnd()) $SMTPAddress = ($SMTPAddress.ToLower()) } #end if ELSE { Write-LogFile -LogLine "There is no E-Mail address in the FROM Attribut of this Mail!" Write-LogFile -LogLine "Summary: Found none valid E-Mail adress(es) for this Mail, via EML Object." Write-LogFile -LogLine "Now trying via EML Sourcecode!" Try { $EMLFileContent = Get-Content $EMLFile $SMTPAddress = ($EMLFileContent | Select-String -Pattern $SMTPDomains -AllMatches | Select -First 1) } #end try Catch { Write-LogFile -LogLine "Cannot get Sourcecode from EMLFile: $EMLFile" } #end catch } #end else IF ($SMTPAddress) { #Filter and remove illegal chars $SMTPAddress = ($SMTPAddress -Replace('\<|\>|\(|\)|\[|\]|\"|\s\,\;\:\=\\','')) $SMTPAddress = ($SMTPAddress -Replace("'","")) $SMTPAddress = ($SMTPAddress -Replace('From','')) $SMTPAddress = ($SMTPAddress.TrimStart()) $SMTPAddress = ($SMTPAddress.TrimEnd()) $SMTPAddress = ($SMTPAddress.ToLower()) $SMTPAddress = ($SMTPAddress.Split(' ')) IF ($SMTPAddress -is [Array] -and ($SMTPAddress[-1])) { $SMTPAddress = $SMTPAddress[-1] $SMTPAddress = $SMTPAddress.ToString() } #end if $SMTPAddress = 'SMTP-Mail-From: '+$SMTPAddress #Replace and add new values to the string $MPRFileContent.RemoveAt($MPRFileContentSMTPIndex) $MPRFileContent.Insert($MPRFileContentSMTPIndex, $SMTPAddress) Try { Write-LogFile -LogLine " " Write-LogFile -LogLine "Creating new and corrected MPR File." New-Item -ItemType "file" $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop Clear-Content $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop $MPRFileContent | Set-Content $TargetPath\$MPRFileBaseName -Force -ErrorAction Stop MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $TargetPath -Action move Write-LogFile -LogLine "Removing old MPR File." Remove-Item -Path $MPRFile -Force -ErrorAction Stop } #end try Catch { Write-LogFile -LogLine "Error, could not write to file:" Write-LogFile -LogLine $MPRFile Write-LogFile -LogLine "Please check your access rights!" } #end catch } #end else ELSE { Write-LogFile -LogLine "Summary: Found none valid E-Mail adress(es) for this Mail, via EML Object or Sourcecode!" } #end else } #end elseif ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "Ivalide MPR File!" Write-LogFile -LogLine "Moving to ErrorPath: $ErrorPath" Try { MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $ErrorPath -Action move MoveOrCopy-Item-withLogging -SourceFile $MPRFile -DestinationPath $ErrorPath -Action move } #end try Catch { Write-LogFile -LogLine "Error, could not move files:" Write-LogFile -LogLine $EMLFile Write-LogFile -LogLine $MPRFile } #end catch } #end else } #end elseif ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "Ivalide MPR File!" Write-LogFile -LogLine "Did not found any POP or SMTP activity in File." Write-LogFile -LogLine "Moving to ErrorPath: $ErrorPath" Try { MoveOrCopy-Item-withLogging -SourceFile $EMLFile -DestinationPath $ErrorPath -Action move MoveOrCopy-Item-withLogging -SourceFile $MPRFile -DestinationPath $ErrorPath -Action move } #end try Catch { Write-LogFile -LogLine "Error, could not move files:" Write-LogFile -LogLine $EMLFile Write-LogFile -LogLine $MPRFile } #end catch } #end else } #end if ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "MPR or EML File seems to be not read- or writeable!" Write-LogFile -LogLine "$MPRFileBaseName -> Test: $FileTest2" Write-LogFile -LogLine "$EMLFileBaseName -> Test: $FileTest3" Write-LogFile -LogLine "Skipping because of this..." } #end else } #end if ELSEIF (($FileTest2 -eq $True) -or ($FileTest3 -eq $True)) { Write-LogFile -LogLine " " Write-LogFile -LogLine "MPR or EML File seems already to exist, in the Target Path!" Write-LogFile -LogLine "$MPRFileBaseName -> Test: $FileTest2" Write-LogFile -LogLine "$EMLFileBaseName -> Test: $FileTest3" Write-LogFile -LogLine "Skipping because of this..." } #end elseif ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "MPR File seems not to exist!" } #end else } #end foreach } #end if #If there are no files, ... just chill ELSE { Write-Logfile -LogLine " " Write-LogFile -LogLine "Found no ($EMLFileExtension) Files in Directory (must be older than $FileDelayAge Minute(s), to be processed):" Write-LogFile -LogLine "$SourcePath" Write-LogFile -LogLine "... so there is nothing to do yet, exiting." } #end else } #end if ELSE { Write-LogFile -LogLine " " Write-LogFile -LogLine "Invalid Source or Target Path, or access denied on:" Write-LogFile -LogLine "$SourcePath Test: $PathTest" Write-LogFile -LogLine "$TargetPath Test: $PathTest2" } #end else IF ($TargetPathErrorFileDelayAge -gt 0) { $Items = (Get-ChildItem -Path $TargetPath -Filter "*.$EMLFileExtension, *.$MPRFileExtension" | where {$_.lastwritetime -lt $((Get-Date).AddDays(-$TargetPathErrorFileDelayAge)) -and -not $_.psiscontainer}) FOREACH ($Item in $Items) { MoveOrCopy-Item-withLogging -SourceFile $Item -DestinationPath $TargetPath -Action move } #end foreach } #end if Write-Logfile -LogLine " " Write-Logfile -LogLine "--------------------------------------------------------------------------------" Write-Logfile -LogLine "Checking for old LogFiles." Write-Logfile -LogLine "--------------------------------------------------------------------------------" Remove-Item-withLogging -Path $LogPath -FileKeepTime $LogFileKeepTime -FileBaseName $ScriptName Write-Logfile -LogLine " " Write-Logfile -LogLine "********************************************************************************" Write-Logfile -LogLine "Program Completed: $ScriptName on $env:COMPUTERNAME," Write-Logfile -LogLine "from Account $env:USERDOMAIN\$env:USERNAME." Write-Logfile -LogLine "********************************************************************************" #-----------------------------------------------------------------------------------------------------# ########################################### finishing part ############################################ #-----------------------------------------------------------------------------------------------------# Remove-Variable -Name ScriptName -Force -ErrorAction SilentlyContinue Remove-Variable -Name ScriptPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name ConfigFile -Force -ErrorAction SilentlyContinue Remove-Variable -Name ConfigValues -Force -ErrorAction SilentlyContinue Remove-Variable -Name Timestamp1 -Force -ErrorAction SilentlyContinue Remove-Variable -Name Timestamp2 -Force -ErrorAction SilentlyContinue Remove-Variable -Name Timestamp3 -Force -ErrorAction SilentlyContinue Remove-Variable -Name Timestamp4 -Force -ErrorAction SilentlyContinue Remove-Variable -Name Item -Force -ErrorAction SilentlyContinue Remove-Variable -Name Items -Force -ErrorAction SilentlyContinue Remove-Variable -Name VersionSeperator -Force -ErrorAction SilentlyContinue Remove-Variable -Name FileDelayAge -Force -ErrorAction SilentlyContinue Remove-Variable -Name FileTest -Force -ErrorAction SilentlyContinue Remove-Variable -Name FileTest2 -Force -ErrorAction SilentlyContinue Remove-Variable -Name FileTest3 -Force -ErrorAction SilentlyContinue Remove-Variable -Name PathTest -Force -ErrorAction SilentlyContinue Remove-Variable -Name PathTest2 -Force -ErrorAction SilentlyContinue Remove-Variable -Name PathTests -Force -ErrorAction SilentlyContinue Remove-Variable -Name Result -Force -ErrorAction SilentlyContinue Remove-Variable -Name Counter1 -Force -ErrorAction SilentlyContinue Remove-Variable -Name LogFile -Force -ErrorAction SilentlyContinue Remove-Variable -Name LogFileKeepTime -Force -ErrorAction SilentlyContinue Remove-Variable -Name LogPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name LogPaths -Force -ErrorAction SilentlyContinue Remove-Variable -Name Module -Force -ErrorAction SilentlyContinue Remove-Variable -Name Modules -Force -ErrorAction SilentlyContinue Remove-Variable -Name ModuleOverrideSourcePath -Force -ErrorAction SilentlyContinue Remove-Variable -Name ModuleDefaultSourcePath -Force -ErrorAction SilentlyContinue Remove-Variable -Name ModuleHKLMRegistryPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name ModuleHKCURegistryPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name SMTPDomain -Force -ErrorAction SilentlyContinue Remove-Variable -Name SMTPDomains -Force -ErrorAction SilentlyContinue Remove-Variable -Name SMTPDomainsTEMP -Force -ErrorAction SilentlyContinue Remove-Variable -Name SMTPAddress -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddresses -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressTO -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressesTO -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressCC -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressesCC -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressBCC -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressesBCC -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressTEMP -Force -ErrorAction SilentlyContinue Remove-Variable -Name POPAddressesTEMP -Force -ErrorAction SilentlyContinue Remove-Variable -Name SourcePath -Force -ErrorAction SilentlyContinue Remove-Variable -Name TargetPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name ErrorPath -Force -ErrorAction SilentlyContinue Remove-Variable -Name EMLFile -Force -ErrorAction SilentlyContinue Remove-Variable -Name EMLFileBaseName -Force -ErrorAction SilentlyContinue Remove-Variable -Name EMLFileExtension -Force -ErrorAction SilentlyContinue Remove-Variable -Name EMLFileContent -Force -ErrorAction SilentlyContinue Remove-Variable -Name EMLObject -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFile -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileBaseName -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileExtension -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileContent -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileContentPOPValue -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileContentPOPIndex -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileContentSMTPValue -Force -ErrorAction SilentlyContinue Remove-Variable -Name MPRFileContentSMTPIndex -Force -ErrorAction SilentlyContinue Remove-Variable -Name TargetPathErrorFileDelayAge -Force -ErrorAction SilentlyContinue $error.clear()