# PowerShell 4.0 Script # This is a simple PowerShell Script to move or copy files. # For this, you can set Profiles in _Settings.ini. # Digital Data # Ludwig-Rinn-Strasse 16 # 35452 Heuchelheim # Tel.: 0641 / 202360 # E-Mail: info@digitaldata.works # Version Number: 1.5.0.0 # Version Date: 21.02.2024 # Minimum Requirement for this Script: # Microsoft Windows XP SP3 / Server 2008 R2 SP1 -> look at KB976932 # Microsoft .NET Framework 4.5 -> look at KB2858728 # Microsoft PowerShell 4.0 -> look at KB2819745 # WICHTIG: Falls sich dieses Skript nicht ausführen lässt, # gibt es mehrere Möglichkeiten die Ausführung zuzulassen. # Zwei Möglichkeiten lauten wie folgt: # # 1. PowerShell Skripte generell erlauben. # Dazu muss dieser PowerShell-Befehl noch mit administrativen Rechten ausgeführt werden: # "set-executionpolicy unrestricted" # # 2. Die Ausführungseinschränkung für dieses Skript durch einen veränderten Aufruf umgehen: # PowerShell.exe -ExecutionPolicy Bypass -File #Requires –Version 4.0 #-----------------------------------------------------------------------------------------------------# ######################################## check for arguments ########################################## #-----------------------------------------------------------------------------------------------------# Param ( [Parameter(Mandatory=$False)] [ValidateSet("copy", "move")] [String]$argOperation, [Parameter(Mandatory=$False)] [ValidateNotNull()] [String]$argFileTypes, [Parameter(Mandatory=$False)] [ValidateNotNull()] [String]$argSourcePath, [Parameter(Mandatory=$False)] [ValidateNotNull()] [String]$argDestinationPath, [Parameter(Mandatory=$False)] [AllowNull()] [Int]$argFileDelayAge ) #end Param #-----------------------------------------------------------------------------------------------------# ###################################### add additional assemblys ####################################### #-----------------------------------------------------------------------------------------------------# [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") #-----------------------------------------------------------------------------------------------------# ############################################ set variables ############################################ #-----------------------------------------------------------------------------------------------------# Set-Variable -Name ScriptName -Value (($MyInvocation.MyCommand.Name) -split "\.")[0].ToString() -Scope script Set-Variable -Name ScriptPath -Value (Split-Path ($MyInvocation.MyCommand.Path)) -Scope script Set-Variable -Name ConfigFile -Value "$ScriptPath\$ScriptName`_Settings.ini" -Scope script Set-Variable -Scope Global -Name ConfigFileContent -Value $NULL Set-Variable -Name KonfigWerte -Value $NULL -Scope script Set-Variable -Name ZeitStempel1 -Value $(Get-Date -Format 'ddMMyyyy_HHmmss') -Scope script Set-Variable -Name Fehler -Value $NULL -Scope local Set-Variable -Name LogDatei -Value "$ScriptName`_$ZeitStempel1.log" -Scope script Set-Variable -Name LogLine -Value $NULL -Scope local Set-Variable -Name LogPathListe -Value $NULL -Scope script Set-Variable -Name LogPath -Value $NULL -Scope script Set-Variable -Name LogPathEintrag -Value $NULL -Scope script Set-Variable -Name LogFileKeepTime -Value 60 -Scope script Set-Variable -Name FileDelayAge -Value 5 -Scope script Set-Variable -Name Item -Value $NULL -Scope local Set-Variable -Name ItemMoved -Value $NULL -Scope local Set-Variable -Name Items -Value $NULL -Scope local Set-Variable -Name ItemsMoved -Value $NULL -Scope local Set-Variable -Name Path -Value $NULL -Scope local Set-Variable -Name PathTest -Value $NULL -Scope local Set-Variable -Name ProzessTest -Value $NULL -Scope local Set-Variable -Name VersionSeperator -Value '~' -Scope local Set-Variable -Name Counter -Value $NULL -Scope local Set-Variable -Name FileTypes -Value $NULL -Scope script Set-Variable -Name FileCheckResult -Value $NULL -Scope script Set-Variable -Name FileWhiteList -Value $NULL -Scope script Set-Variable -Name FileBlackList -Value $NULL -Scope script Set-Variable -Name FileSeperator -Value '' -Scope script Set-Variable -Name FileCheckCounter -Value $NULL -Scope script Set-Variable -Name FileCheckCounterLimit -Value 1000 -Scope script Set-Variable -Name MoveOrCopy -Value $NULL -Scope script Set-Variable -Name SourcePath -Value $NULL -Scope script Set-Variable -Name DestinationPathTemplate -Value $NULL -Scope script Set-Variable -Name DestinationPath -Value $NULL -Scope script Set-Variable -Name MinimumNumOfParams -Value 4 -Scope Script Set-Variable -Name DateSeperator -Value "/" -Scope Script Set-Variable -Name ReclusiveSwitch -Value $false -Scope Script Set-Variable -Scope Global -Name Module -Value $NULL Set-Variable -Scope Global -Name Modules -Value ("Read-ConfigFile2") Set-Variable -Scope Global -Name Mount -Value $NULL #-----------------------------------------------------------------------------------------------------# ############################################ 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 (optional) .REQUIREMENT Functions .VERSION 1.1.0.0 / 22.02.2017 .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 ModuleFileExtensions Optional Parameter. Give the Module File-Extension (regular: "psm1" or "dll") 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 -ModuleFileExtensions psm1 .EXAMPLE Load-PowerShellModule -ModuleName Write-LogFile -Force .EXAMPLE Load-PowerShellModule -ModuleName Write-LogFile -ModuleFileExtensions psm1 -ModuleOverrideSourcePath D:\ScriptFiles\Modules #> 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(Position=1,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(Position=2,Mandatory=$False,HelpMessage='Optional Parameter. Give the Module File-Extension (regular: "psm1" or "dll") without a dot ("."), this is just for the checking routine, not the Import itself.')] [ValidateSet("psm1","dll")] [Array]$ModuleFileExtensions = @("psm1","dll"), [Parameter(Position=3,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() #Loop for every possible File Extension (eg. psm1 and dll) FOREACH ($ModuleFileExtension in $ModuleFileExtensions) { #If FileExtension was given, remove it! Because otherwise "Import-Module" Function will have trouble importing. $ModuleName = $ModuleName -Replace("\.[a-zA-Z0-9]{3,4}","") Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: You want to load Module $ModuleName.$ModuleFileExtension" IF ((([String]::IsNullOrWhiteSpace($ScriptName) -ne $True) -and ([String]::IsNullOrEmpty($ScriptName) -ne $True)) -and (([String]::IsNullOrWhiteSpace($ScriptPath) -ne $True) -and ([String]::IsNullOrEmpty($ScriptPath) -ne $True))) { #Try this if $ModuleOverrideSourcePath was given by calling the function IF ((([String]::IsNullOrWhiteSpace($ModuleOverrideSourcePath)) -ne $True) -and (([String]::IsNullOrEmpty($ModuleOverrideSourcePath)) -ne $True)) { 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" $FileTest = Test-Path -Path "$ModuleOverrideSourcePath\$ModuleName.$ModuleFileExtension" -PathType Leaf IF ($FileTest -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 -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 Module 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 ((([String]::IsNullOrWhiteSpace($($Paths[$Counter]))) -ne $True) -and (([String]::IsNullOrEmpty($($Paths[$Counter])) -ne $True))) { $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) $ModuleFileExtension 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])) { $FileTest = (Test-Path -Path $ModuleSourcePath\$ModuleName.$ModuleFileExtension -PathType Leaf -ErrorAction SilentlyContinue) IF ($FileTest -eq $True) { 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 -ErrorAction SilentlyContinue IF ("$Result" -eq "$ModuleName") { Write-Host "DEBUG Info - Load-PowerShellModule: Successfully loaded Module: $ModuleName.$ModuleFileExtension" Set-Variable -Name ModuleDefaultSourcePath -Value $ModuleSourcePath -Scope Global 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: Module does not exist!" Write-Host "DEBUG Info - Load-PowerShellModule: Skipping: $ModuleName.$ModuleFileExtension" } #end else } #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." $FileTest = (Test-Path $ModuleSourcePath\$ModuleName.$ModuleFileExtension -PathType Leaf -ErrorAction SilentlyContinue) IF ($FileTest -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 -ErrorAction SilentlyContinue IF ("$Result" -eq "$ModuleName") { Set-Variable -Name ModuleDefaultSourcePath -Value $ModuleSourcePath -Scope Global $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 ((($FileTest -eq $True) -and ($? -eq $True)) -or ($FolderBrowserDialogShow -eq "Cancel")) IF (([String]::IsNullOrWhiteSpace($ModuleSourcePath) -ne $True) -and ([String]::IsNullOrEmpty($ModuleSourcePath) -ne $True)) { 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" -ErrorAction SilentlyContinue) $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 -ErrorAction Stop | Out-Null New-ItemProperty -Path "$ModuleHKLMRegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -ErrorAction Stop | Out-Null } #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 -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" -ErrorAction SilentlyContinue) $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 -ErrorAction Stop | Out-Null New-ItemProperty -Path "$ModuleHKCURegistryPath" -Name ModuleSourcePath -Value $ModuleSourcePath -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 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 -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 if ELSE { Write-Host "" Write-Host "DEBUG Info - Load-PowerShellModule: Required Variables (ScriptName and ScriptPath) were not set!" Write-Host "DEBUG Info - Load-PowerShellModule: Module Import is unvailable without this Variables!" } #end else } #end foreach } #end process } #end function Function Func-Path-Check { <# .SYNOPSIS Function will check the given Path for existence. .DESCRIPTION Function will check the given Path for existence. If Path isn´t existence Function will try to create it. .REQUIREMENT General PowerShell V2 and Function "Func-Write-Logfile". .REQUIREMENT Variables Path, PathTest .VERSION 1.0 / 06.11.2014 .EXAMPLE Func-Path-Check -Path "E:\Path\to\check" .EXAMPLE Func-Path-Check -Path "E:\Path\to\create" .PARAMETER Path Give the full Path you want to check or create. #> Param ( [String]$Path ) $PathTest = Test-Path -PathType Container $Path Func-Write-Logfile -LogLine "Checking Path $Path for existence." IF ($PathTest -eq "True") { Func-Write-Logfile -LogLine "Path $Path is already existence and can be used." } ELSE { Try { Func-Write-Logfile -LogLine "Path $Path has to been created." New-Item -Path $Path -ItemType directory -force -ErrorAction Stop } Catch { Func-Write-Logfile -LogLine "ERROR: Unable to create Path." Func-Write-Logfile -LogLine "INFO: Maybe there is an access or rights Problem." Func-Write-Logfile -LogLine "Application was unplannd terminated." EXIT } } } #end function Function Func-Write-Logfile { <# .SYNOPSIS Function will write a given String to a Logfile. .DESCRIPTION Function will write a given String to a Logfile. It will even log Error Messages. .REQUIREMENT General PowerShell V2 .REQUIREMENT Variables LogPathListe, LogPathEintrag, LogPath, Fehler, Pfad-Test .VERSION 1.0 / 06.11.2014 .EXAMPLE Func-Path-Check -Log "Write this in my Log, please." .EXAMPLE Func-Path-Check -Log "Write this Variabel $Variable in my Log, please." .PARAMETER Log Give the Sting you want to be written in the Logfile. #> Param ( [string]$LogLine ) # Der Fehlerindikator ($?) muss bereits zu Anfang abgefragt werden, # da er von JEDEM funktionierenden Befehl wieder auf True gesetzt wird. IF ($? -ne 'True') { Set-Variable -Name Fehler -Value 1 } IF ($LogPath -eq $NULL) { Set-Variable -Name LogPathListe -Value @($LogPathListe) Set-Variable -Name LogPathListe -Value ($LogPathListe += "$ScriptPath\Logs","$env:temp") FOREACH ($LogPathEintrag in $LogPathListe) { $PfadTest = Test-Path -PathType Container "$LogPathEintrag" Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: Prüfe ob LogPath bereits angelegt ist: $LogPathEintrag" IF ($PfadTest -eq "True") { Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: LogPath $LogPathEintrag ist bereits angelegt!" Set-Variable -Name LogPath -Value $LogPathEintrag break } ELSE { Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: LogPath $LogPathEintrag muss angelegt werden." New-Item -Path $LogPathEintrag -ItemType directory -force -ErrorAction SilentlyContinue | Out-Null $PfadTest = Test-Path -PathType Container $LogPathEintrag Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: Prüfe ob Pfad erfolgreich angelegt werden konnte." IF ($PfadTest -eq "True") { Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: Pfad $LogPathEintrag wurde erfolgreich angelegt." Set-Variable -Name LogPath -Value $LogPathEintrag break } ELSE { Write-Host "DEBUG Info: Write-Logfile - Pfadüberprüfung: Pfad $LogPathEintrag konnte nicht angelegt werden." Set-Variable -Name LogPath -Value $LogPathEintrag } } } } ELSEIF ($LogPath -eq $env:temp) { Write-Warning "FEHLER: LogPath nicht zugreifbar oder nicht korrekt konfiguriert!" Write-Warning "INFO: $LogPath - wird nun verwendet!" Write-Warning "Programm wird trotzdem fortgesetzt." } Set-Variable -Name LogPath -Value $LogPath -scope script Write-Host $LogLine Add-content $LogPath\$LogDatei -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): $LogLine" IF ($Fehler -eq 1) { Write-Host "Fehlermeldung: $error" Add-content $LogPath\$LogDatei -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): Fehlermeldung: $error" # Setze Fehlerspeicher zurück $error.clear() } } #end function Function Func-ReadConfigFile { Param ( [String]$ConfigFile ) Write-Host "" Write-Host "Prüfe ob Konfigurationsdatei: $ConfigFile vorhanden ist." $DateiTest = Test-Path -PathType Leaf $ConfigFile IF ($DateiTest -eq "True") { Write-Host "DEBUG Info: ReadConfigFile - Konfigurationsdatei ist vorhanden, fahre fort." } ELSE { Func-Write-Logfile -LogLine "FEHLER: Konfigurationsdatei ist nicht vorhanden!" Func-Write-Logfile -LogLine "Programm wird ungeplant beendet." EXIT } Write-Host "Konfigurationsdatei wird nun eingelesen." Set-Variable -Name KonfigWerte -Value (Select-String -path $ConfigFile -pattern "=" | where {-not($_-match "#")}) IF ($KonfigWerte -eq $Null) { Write-Host "DEBUG Info: ReadConfigFile - Keine gültigen Werte in Konfigurationsdatei erkannt!" } ELSE { Write-Host "Es wurden"$KonfigWerte.count"Zeilen aus der Konfigurationsdatei eingelesen." #Write-Host "Folgende Werte wurden eingelesen:" #Write-Host "$KonfigWerte" #pause } Set-Variable -Name KonfigWerte -Value $KonfigWerte -Scope script } #end function Function Func-ReadConfigValue { Param ( [String]$KonfigBezeichner ) $Items = ($KonfigWerte.line | select-string -pattern "$KonfigBezeichner") IF ($Items -eq $NULL) { Write-Host "Der gesuchte Bezeichner ($KonfigBezeichner) konnte nicht gefunden werden!" Write-Host "Standardwert wird verwendet!" $KonfigBezeichner = (Get-Variable -Name $KonfigBezeichner -ValueOnly) return $KonfigBezeichner } ELSEIF ($Items.GetType() -like "*Microsoft.PowerShell.Commands.MatchInfo*" -or $Items.GetType() -like "*String*") { $Items = ($Items -split "=") $Items = @($Items) $Items = $Items[1] $Items = ($Items.TrimStart()) $Items = ($Items.TrimEnd()) return $Items } ELSEIF ($Items -is [Array]) { return $Items } } #end function Function Func-File-Collector { <# .SYNOPSIS Function will check the given Path for existence. .DESCRIPTION Function will check the given Path for existence. It returns always just ONE Value! .REQUIREMENT General PowerShell V2 and Function "Func-Write-Logfile". .REQUIREMENT Variables Path, PathTest .REQUIREMENT Functions .VERSION Number: 1.1.0.0 / Date: 23.09.2015 Update 21.04.2021 -> ReclusiveSwitch .EXAMPLE Func-Path-Check -Path "E:\Path\to\check" .EXAMPLE Func-Path-Check -Path "E:\Path\to\create" .PARAMETER Path Give the full Path you want to check or create. #> Param ( [String]$SearchPath, [Array]$SearchWhiteList, [Array]$SearchBlackList, [String]$ReclusiveSwitch ) Set-Variable -Name SearchWhiteList -Value ($SearchWhiteList -Replace " ","") Set-Variable -Name SearchWhiteList -Value ($SearchWhiteList -Split ",") Set-Variable -Name SearchWhiteList -Value ($SearchWhiteList -Split ";") Set-Variable -Name SearchBlackList -Value ($SearchBlackList -Replace " ","") Set-Variable -Name SearchBlackList -Value ($SearchBlackList -Split ",") Set-Variable -Name SearchBlackList -Value ($SearchBlackList -Split ";") IF (($ReclusiveSwitch -eq $true) -or ($ReclusiveSwitch -eq "true") -or ($ReclusiveSwitch -eq "treu") -or ($ReclusiveSwitch -eq 1) -or ($ReclusiveSwitch -eq "yes")) { Func-Write-Logfile -LogLine "Searching reclusive in $SearchPath" $Items = Get-ChildItem -Path $SearchPath -include $SearchWhiteList -exclude $SearchBlackList -Recurse:$true | where { ! $_.PSIsContainer } Write-Host "DEBUG Info: Found $($Items.count)" } #end if Else { Func-Write-Logfile -LogLine "Searching NOT reclusive in $SearchPath" $Items = Get-ChildItem -Path $SearchPath -include $SearchWhiteList -exclude $SearchBlackList -Recurse:$false | where { ! $_.PSIsContainer } Write-Host "DEBUG Info: Found $($Items.count)" } #end else IF ($Items -eq $NULL) { Func-Write-Logfile -LogLine "Could not find any File(s) in Path: $SearchPath (regard on White and Black Lists)." } #end if ELSE { Func-Write-Logfile -LogLine "Could find some File(s) - $($Items.count) - in Path: $SearchPath (regard on White and Black Lists) ..." #FOREACH ($Item in $Items) { # Func-Write-Logfile -LogLine "...found File: $Item" #} #end foreach Return $Items } #end else } #end function Function Func-File-check-state { <# .SYNOPSIS Function will check if given file is accessible for this Script. .DESCRIPTION Function will check if given file is accessible for this Script. .REQUIREMENT General PowerShell V2 .REQUIREMENT Variables FilePath_and_FileName, filechecktyp, fileInfo, filecheckresult, filestream .REQUIREMENT Functions Func-Write-Logfile .VERSION Number: 1.0.1.0 / Date: 05.02.2016 .EXAMPLE Func-File-check-state -FilePath_and_FileName "E:\Path\file_to_check.txt" .EXAMPLE Func-File-check-state -FilePath_and_FileName "E:\Path\file_to_check.txt" -filechecktyp write .PARAMETER FilePath_and_FileName Give the full Path to the file you want to check. .PARAMETER filechecktyp Optional: If you want an additional writetest (readtest is always first action), give this parameter with Value "write". #> Param ( [String]$FilePath_and_FileName, [String]$filechecktyp ) IF ((Test-Path -Path $FilePath_and_FileName) -eq 'True') { Set-Variable -Name fileInfo -Value (New-Object System.IO.FileInfo $FilePath_and_FileName) -Scope local Set-Variable -Name filecheckresult -Value "unknown" -Scope local Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Checking if file: $FilePath_and_FileName is locked..." Func-Write-Logfile -LogLine "Checking if file: $FilePath_and_FileName 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 IF ($fileStream.CanRead -eq $true) { Set-Variable -Name filecheckresult -Value "readable" } #end if ELSE { Set-Variable -Name filecheckresult -Value "notreadable" } #end else $filestream.Close() } #end try catch { Func-Write-Logfile -LogLine "File: $FilePath_and_FileName is not even readable." Write-Host "DEBUG Info: Is file readable?" $filestream.CanRead $filestream.Close() Set-Variable -Name filecheckresult -Value "notreadable" } #end catch # Check if file is writeable IF (($filecheckresult -eq "readable") -and ($filechecktyp -eq 'write')) { Func-Write-Logfile -LogLine "Checking if file: $FilePath_and_FileName 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 IF ($fileStream.CanWrite -eq $true) { Set-Variable -Name filecheckresult -Value "writeable" } #end if ELSE { Set-Variable -Name filecheckresult -Value "notwriteable" } #end else $filestream.Close() } #end try Catch { Func-Write-Logfile -LogLine "File: $FilePath_and_FileName is not writeable." Write-Host "DEBUG Info: Is file writeable?" $filestream.CanWrite $filestream.Close() Set-Variable -Name filecheckresult -Value "notwriteable" } #end catch } #end if Func-Write-Logfile -LogLine "File $FilePath_and_FileName checked with result: $FileCheckResult" Return $FileCheckResult } #end if ELSE { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Given file: $FilePath_and_FileName seems not to exist, or access is denied." Set-Variable -Name filecheckresult -Value "unavailable" Return $FileCheckResult } #end else } #end function Function Move-or-Copy-Item-withLogging { <# .SYNOPSIS Function will copy or move File(s). .DESCRIPTION Function will copy or move File(s). If File already exists in target Path new File will get a Version ~2. .REQUIREMENT General PowerShell V2 .REQUIREMENT Variables Datei, Datei1, DateiName, DateiEndung, DateiTest, DateiVersion,ZielPath, MoveorCopy, SourcePath .REQUIREMENT Functions Func-Write-Logfile, .VERSION 1.2 / 15.09.2015 .EXAMPLE Func-File-copy-or-move -FilePath_and_FileName "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy move .EXAMPLE Func-File-copy-or-move -FilePath_and_FileName "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy copy .PARAMETER $FilePath_and_FileName 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 $move_or_copy Give this Parameter to determ a copy or a move Order. #> Param ( [String]$FilePath_and_FileName, [String]$DestinationPath, [String]$move_or_copy, [String]$NewfileName, [String]$NewFileName_prefix, [String]$NewFileName_suffix ) Func-Write-Logfile -LogLine "" Set-Variable -Name SourcePath -Value ([System.IO.Path]::GetDirectoryName($FilePath_and_FileName).ToString()) Set-Variable -Name FileName -Value ([System.IO.Path]::GetFileName($FilePath_and_FileName).ToString()) Set-Variable -Name FileName_noExt -Value ([System.IO.Path]::GetFileNameWithoutExtension($FilePath_and_FileName).ToString()) Set-Variable -Name FileExtension -Value ([System.IO.Path]::GetExtension($FilePath_and_FileName).ToString()) IF (($move_or_Copy -ne 'move') -and ($move_or_copy -ne 'copy')) { Func-Write-Logfile -LogLine "ERROR: Wrong Function call." Func-Write-Logfile -LogLine "INFO: Parameter move_or_copy accepts only 'move' or 'copy'." Func-Write-Logfile -LogLine "Application will use the copy Order by default." Set-Variable -Name move_Or_copy -Value copy -Scope local } #end if IF (($VersionSeperator -eq $null) -or ($VersionSeperator -eq '')) { Func-Write-Logfile -LogLine "ERROR: Wrong Function call." Func-Write-Logfile -LogLine "INFO: Variable VersionSeperator is not valid." Func-Write-Logfile -LogLine "Application was unplannd terminated." EXIT } #end if IF ($newfilename -gt ' ') { Func-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 -gt ' ') { Func-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 -gt ' ') { Func-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? Set-Variable -Name FileTest -Value (Test-Path -PathType Leaf "$DestinationPath\$FileName") IF ($Filetest -eq 'True') { Func-Write-Logfile -LogLine "The File ($Filename) already exists in the target directory, starting Version Check." $FileVersion = $NULL -as [Int] Set-Variable -Name FileNameSplit -Value ($Filename_noExt -split "$VersionSeperator") Set-Variable -Name FileVersion -Value $FileNameSplit[1] $FileVersion = $FileVersion -as [Int] # 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." Set-Variable -Name FileName_noExt -Value $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 "$FilePath_and_FileName" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""}) Set-Variable -Name FileTemp -Value (Copy-Item -Path "$FilePath_and_FileName" -Destination "$DestinationPath\$Timestamp3`_$FileName" -PassThru -Force) Func-Write-Logfile -LogLine "The $move_or_copy command has been completed." Set-Variable -Name FileFinal -Value (Rename-Item -Path "$FileTemp" -NewName "$FileName_noExt$VersionSeperator$FileVersion$FileExtension" -PassThru -Force ) Func-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 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 ($move_or_copy -eq 'move') { Write-Host "DEBUG Info: Moving action was choosen, will delete source file." IF ($FileHash_befor -eq $FileHash_after) { Try { Remove-Item -Path "$FilePath_and_FileName" -Force } #end try Catch { Func-Write-Logfile -LogLine "Error removing the source file." } #end catch } #end if ELSE { Func-Write-Logfile -LogLine "HASH Value does mismatch!" Func-Write-Logfile -LogLine "Aborting delete operation!" } #end else } #end if Return $FileFinal.Fullname } #end try Catch { Func-Write-Logfile -LogLine "Error at $move_or_copy command, processing file: $FilePath_and_FileName" Func-Write-Logfile -LogLine "Please check your privileges" exit } #end catch ELSEIF ($MoveorCopy -eq 'copy') { Write-Host "DEBUG Info: Coping action was choosen, will not delete original file." } #end elseif } #end if ELSE { Set-Variable -Name FileHash_befor -Value (Get-FileHash -Path "$FilePath_and_FileName" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""}) Set-Variable -Name FileFinal -Value (Copy-Item -Path "$FilePath_and_FileName" -Destination "$DestinationPath\$FileName" -PassThru -Force) Set-Variable -Name FileHash_after -Value (Get-FileHash -Path "$FileFinal" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""}) Func-Write-Logfile -LogLine "The $move_or_copy command has been completed for file: $FilePath_and_FileName" Func-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 ($move_or_copy -eq 'move') { Write-Host "DEBUG Info: Moving action was choosen, will delete source file." IF ($FileHash_befor -eq $FileHash_after) { Try { Remove-Item -Path "$FilePath_and_FileName" -Force } #end try Catch { Func-Write-Logfile -LogLine "Error removing the source file." } #end catch } #end if ELSE { Func-Write-Logfile -LogLine "HASH Value does mismatch!" Func-Write-Logfile -LogLine "Aborting delete operation!" } #end else } #end if ELSEIF ($Move_or_Copy -eq 'copy') { Write-Host "DEBUG Info: Coping action was choosen, will not delete original file." } #end elseif Return $FileFinal.Fullname } #end else } #end function #-----------------------------------------------------------------------------------------------------# ########################################### preparing part ############################################ #-----------------------------------------------------------------------------------------------------# # Lösche evtl. anzeigen. 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 successful 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 and load its content into a Object [OBJECT]$ConfigFileContent = Read-ConfigFile2 -ConfigFile $ConfigFile # Konfigurationsdatei komplett einlesen. Func-ReadConfigFile -ConfigFile $ConfigFile # Werte aus Konfigurationsdatei bereitstellen. Set-Variable -Name LogPathListe -Value (Func-ReadConfigValue -KonfigBezeichner LogPath) Set-Variable -Name LogFileKeepTime -Value (Func-ReadConfigValue -KonfigBezeichner LogFileKeepTime) Set-Variable -Name FileDelayAge -Value (Func-ReadConfigValue -KonfigBezeichner FileDelayAge) Set-Variable -Name VersionSeperator -Value (Func-ReadConfigValue -KonfigBezeichner VersionSeperator) Set-Variable -Name FileCheckCounterLimit -Value (Func-ReadConfigValue -KonfigBezeichner FileCheckCounterLimit) #By the "normal" way Script will use Profile settings from the _Settings.ini config file... If (($PSBoundParameters.values | Measure-Object | Select-Object -ExpandProperty Count) -lt $MinimumNumOfParams) { Try { #Create Object for Profile, the most Propertys of it will be rewritten in the main loop [OBJECT]$MountProfile = New-Object PSObject -ErrorAction Stop Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name Counter -Value 0 -ErrorAction Stop Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name Count -Value "$($ConfigFileContent.MountProfile[0])" -ErrorAction Continue Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name RemotePath -Value $NULL -ErrorAction Stop Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name LocalPath -Value $NULL -ErrorAction Stop Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name Username -Value $NULL -ErrorAction Stop Add-Member -InputObject $MountProfile -MemberType NoteProperty -Name Password -Value $NULL -ErrorAction Stop } #end try Catch { Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "Error creating Object for: MountProfile" Func-Write-Logfile -LogLine "Property Value is missing or invalid!" #Removeing incomplete Object Remove-Variable -Name MountProfile -Force -ErrorAction SilentlyContinue } #end catch Set-Variable -Name MOCF_ProfileList -Value (Func-ReadConfigValue -KonfigBezeichner MOCF_Profile??) FOREACH ($MOCF_Profile in $MOCF_ProfileList) { Write-Host "" Write-Host "DEBUG Info: Folgende Zeilen wurden ausgelesen: --> $MOCF_Profile <--" $Counter = $Counter -as [int] $Counter++ | Out-Null #If Counter is less then 10, we need to fill it with a zero IF ($counter -lt 10) { $counter = $counter -as [String] $counter = ("0"+$counter) } #end if IF ($MOCF_Profile -is [String]) { $MOCF_Profile = @($MOCF_Profile) $MOCF_Profile = ($MOCF_Profile -split ";") #$MOCF_Profile = ($MOCF_Profile -split ",") } #end if ELSE { $MOCF_Profile = @($MOCF_Profile) $MOCF_Profile = ($MOCF_Profile -Split "=" ) $MOCF_Profile = ($MOCF_Profile[1]) $MOCF_Profile = ($MOCF_Profile -split ";") #$MOCF_Profile = ($MOCF_Profile -split ",") } #end else [System.Collections.ArrayList]$MOCF_ProfileValues = @() # Split an merge Array to remove blanks FOREACH ($MOCF_ProfileValue in $MOCF_Profile) { $MOCF_ProfileValue = ($MOCF_ProfileValue.TrimStart()) $MOCF_ProfileValue = ($MOCF_ProfileValue.TrimEnd()) $MOCF_ProfileValues.Add($MOCF_ProfileValue) } #end foreach IF ($MOCF_ProfileValues -eq $NULL) { Write-Host "DEBUG Info: Der erwarteter Wert ist leer!" Write-Host "DEBUG Info: Standardwert wird eingetragen!" Set-Variable -Name ("MOCF_Profile"+$Counter) -value "Standard" -Scope script } #end if ELSE { Write-Host DEBUG Info: ("MOCF_Profile"+$Counter) wurde als Variable gesetzt und hat folgende Werte bekommen: $MOCF_ProfileValues Set-Variable -Name ("MOCF_Profile"+$Counter) -value $MOCF_ProfileValues -Scope script } #end else } #end foreach } #end if #...but if there are enought runtime arguments/parameters, Script will only use them instead of the Profile Settings. ELSE { Func-Write-Logfile -LogLine "Script was called with Arguments, so Profiles in the _Settings.ini will be ignored!" Write-Host "DEBUG Info: $argOperation $argFileTypes $argSourcePath $argDestinationPath $argFileDelayAge" $MOCF_Profile01 = @("$argOperation","$argFileTypes","$argSourcePath","$argDestinationPath","'%FileDelayAge'$argFileDelayAge") $MOCF_ProfileList = "MOCF_Profile01" } #end else #-----------------------------------------------------------------------------------------------------# ############################################# main part ############################################### #-----------------------------------------------------------------------------------------------------# #Clear Error Variable $Error.Clear() | Out-Null #Clear Console Output Clear-Host Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "********************************************************************************" Func-Write-Logfile -LogLine "Program Startup: $ScriptName on $env:COMPUTERNAME," Func-Write-Logfile -LogLine "from Account $env:USERDOMAIN\$env:USERNAME." Func-Write-Logfile -LogLine "********************************************************************************" IF ($MountProfile.Count -gt 0) { Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "Found $($MountProfile.Count) MountProfile(s) to process." #Loop for every MountProfile configured. Every MountProfile is one line in the ConfigFile. DO { $MountProfile.Counter++ | Out-Null Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "--------------------------------------------------------------------------------" Func-Write-Logfile -LogLine "This is MountProfile: $($MountProfile.Counter) of $($MountProfile.Count)" Func-Write-Logfile -LogLine "--------------------------------------------------------------------------------" $MountProfile.RemotePath = ($ConfigFileContent."MountProfile_$($MountProfile.Counter)")[0] Func-Write-Logfile -LogLine "Configured RemotePath is: $($MountProfile.RemotePath)" $MountProfile.LocalPath = ($ConfigFileContent."MountProfile_$($MountProfile.Counter)")[1] Func-Write-Logfile -LogLine "Configured LocalPath is: $($MountProfile.LocalPath)" $MountProfile.Username = ($ConfigFileContent."MountProfile_$($MountProfile.Counter)")[2] Func-Write-Logfile -LogLine "Configured Username is: $($MountProfile.Username)" $MountProfile.Password = ($ConfigFileContent."MountProfile_$($MountProfile.Counter)")[3] If (($MountProfile.RemotePath) -and ($MountProfile.LocalPath) -and ($MountProfile.Username) -and ($MountProfile.Password)) { Try { Func-Write-Logfile -LogLine "Trying to connect: $($MountProfile.RemotePath) ..." $PSCredentialPassword = ConvertTo-SecureString $($MountProfile.Password) -AsPlainText -Force $PSCredential = New-Object System.Management.Automation.PSCredential ($($MountProfile.Username), $PSCredentialPassword) New-PSDrive -Name $MountProfile.LocalPath -PSProvider FileSystem -Root $MountProfile.RemotePath -Credential $PSCredential -Description "Created fom MoveOrCopy Script" -ErrorAction Stop Func-Write-Logfile -LogLine "... now connected to $($MountProfile.LocalPath)" } #end try Catch { Func-Write-Logfile -LogLine "Es ist ein Fehler aufgetreten!" Func-Write-Logfile -LogLine $Error[0].Exception } #end catch } #end if ELSE { Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "Incomplete Profile settings, skipping" continue } } #end do UNTIL ($($MountProfile.Counter) -eq $($MountProfile.Count)) Func-Write-Logfile -LogLine "--------------------------------------------------------------------------------" } #end if ELSE { Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "No MountProfile are defined!" Func-Write-Logfile -LogLine "Check ConfigFile, please." } #end else #If there are some defined Profiles, starte the main part of this Script. IF (($($MOCF_ProfileList.count) -gt 0)) { Func-Write-Logfile -LogLine " " Func-Write-Logfile -LogLine "There is/are $($MOCF_ProfileList.count) out of 99 Rule(s) to process, starting now." #Reset counter Set-Variable -Name Counter -Value $NULL #Loop for each Profile FOREACH ($MOCF_Profile in $(Get-Variable -Name MOCF_Profile??)) { $Counter = $Counter -as [int] $Counter++ | out-null #If Counter is less then 10, we need to fill it with a zero IF ($counter -lt 10) { $counter = $counter -as [String] $counter = ("0"+$counter) } #end if Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "===========================================================================================" Func-Write-Logfile -LogLine "Processing $((Get-Variable -Name ("MOCF_Profile"+$Counter)).Name) now." Func-Write-Logfile -LogLine "===========================================================================================" Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "These Values are setup: $(Get-Variable -Name ("MOCF_Profile"+$Counter) -ValueOnly)." # Save all given parameters of this profile. Set-Variable -Name MOCF_ProfileValues -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly) -Scope local # Save the first array value in the given parameters of this profile. Set-Variable -Name MoveOrCopy -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[0] -Scope local Write-Host "DEBUG Info: $MoveOrCopy" # Save the second array value in the given parameters of this profile. Set-Variable -Name FileTypes -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[1] -Scope local IF (($FileTypes -match "%not%") -or ($FileTypes -match "%ne%")) { [String]$FileTypes = $FileTypes | Where({$_ -match '%not%' -or $_ -match '%ne%'}) [String]$FileTypes = $FileTypes -replace('%not%','') [String]$FileTypes = $FileTypes -replace('%ne%','') [String]$FileTypes = $FileTypes.TrimStart() [String]$FileTypes = $FileTypes.TrimEnd() [Bool]$FileTypesExculde = $true } #end if ELSE { [Bool]$FileTypesExculde = $false } Write-Host "DEBUG Info: $FileTypes" # Save the third array value in the given parameters of this profile. Set-Variable -Name SourcePath -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[2] -Scope local IF ($SourcePath -match "%Date%") { [String]$SourcePath = ($SourcePath | Where({$_ -match '%Date%'})) [String]$SourcePath = ($SourcePath -replace('%Date%',(Get-Date -Format 'yyyyMMdd'))) Write-Host "DEBUG Info: CurrentDate: $(Get-Date -Format 'yyyyMMdd')" } #end if Write-Host "DEBUG Info: $SourcePath" # Save the fourth array value in the given parameters of this profile. Set-Variable -Name ReclusiveSwitch -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[3] -Scope local Write-Host "DEBUG Info: $ReclusiveSwitch" # Save the fifth array value in the given parameters of this profile. Set-Variable -Name FileCheckTyp -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[4] -Scope local Write-Host "DEBUG Info: $FileCheckTyp" # Save the sixth array value in the given parameters of this profile. Set-Variable -Name DestinationPathTemplate -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[5] -Scope local IF ($DestinationPathTemplate -match "%Date%") { [String]$DestinationPathTemplate = ($DestinationPathTemplate | Where({$_ -match '%Date%'})) [String]$DestinationPathTemplate = ($DestinationPathTemplate -replace('%Date%',(Get-Date -Format 'yyyyMMdd'))) Write-Host "DEBUG Info: CurrentDate: $(Get-Date -Format 'yyyyMMdd')" } #end if Write-Host "DEBUG Info: $DestinationPathTemplate" IF ($MOCF_ProfileValues -match "%FileDelayAge*") { [String]$FileDelayAge = ($MOCF_ProfileValues | Where({$_ -match '%FileDelayAge'})) [String]$FileDelayAge = ($FileDelayAge -replace('%FileDelayAge','')) Write-Host "DEBUG Info: FileDelayAge: $FileDelayAge" } #end if IF ($MOCF_ProfileValues -match "%RegExGroup*") { [String]$RegExGroup = ($MOCF_ProfileValues | Where({$_ -match '%RegExGroup'})) [Int]$RegExGroupIndex = ($MOCF_ProfileValues | Where({$_ -match '%RegExGroup'})).Substring(11,1) [String]$RegExGroup = ($RegExGroup -replace('%RegExGroup','')).Remove(0,1) Write-Host "DEBUG Info: RegExGroup: $RegExGroup" } #end if IF ($MOCF_ProfileValues -match "%Replace*") { [String]$Replace = ($MOCF_ProfileValues | Where({$_ -match '%Replace'})) [String]$Replace = ($Replace -replace('%Replace','')) [Array]$Replace = $Replace -split(',') Write-Host "DEBUG Info: Replace: $Replace" } #end if IF ($MOCF_ProfileValues -match "%Date%") { [String]$MOCF_ProfileValues = ($MOCF_ProfileValues | Where({$_ -match '%Date%'})) [String]$MOCF_ProfileValues = ($MOCF_ProfileValues -replace('%Date%',(Get-Date -Format 'yyyyMMdd'))) Write-Host "DEBUG Info: CurrentDate: $(Get-Date -Format 'yyyyMMdd')" } #end if IF ($SourcePath -contains "%ProcessOnlyLastProfileFiles") { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "This run, is just processing files which are known from the last Profile:" FOREACH ($ItemMoved in $ItemsMoved) { Func-Write-Logfile -LogLine "$ItemMoved" } #end foreach Set-Variable -Name Items -Value $ItemsMoved } #end if ELSE { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "This run, searches for $FileTypes -Files in Folder: $SourcePath" Func-Path-Check -Path $Sourcepath If ($FileTypesExculde -eq $false) { Set-Variable -Name Items -Value (Func-File-Collector -SearchPath "$Sourcepath\*" -SearchWhiteList $FileTypes -ReclusiveSwitch $ReclusiveSwitch | where-object {$_.lastwritetime -lt (get-date).addminutes(-$FileDelayAge)} ) } #end if ELSEIF ($FileTypesExculde -eq $true) { Set-Variable -Name Items -Value (Func-File-Collector -SearchPath $Sourcepath -SearchBlackList $FileTypes -ReclusiveSwitch $ReclusiveSwitch | where-object {$_.lastwritetime -lt (get-date).addminutes(-$FileDelayAge)} ) } #end elseif } #end else #Check for Items for this profile, maybe there is no file, so there is nothing to do! IF (($Items -gt $NULL) -or ($Items -gt '')) { #Set dynamic array for saving last processed File(s). [System.Collections.ArrayList]$ItemsMoved = @() #Loop for each file found in the SourcePath, processing by current profile. FOREACH ($Item in $Items) { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" Func-Write-Logfile -LogLine "Processing file: $Item" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" [Int]$FileCheckCounter = 0 Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Filesystem infos about this item (maybe important for final path): " Func-Write-Logfile -LogLine "Attributes: $($Item.Attributes)" Func-Write-Logfile -LogLine "CreationTime Attribute: $($Item.CreationTime)" Func-Write-Logfile -LogLine "LastAccessTime Attribute: $($Item.LastAccessTime)" Func-Write-Logfile -LogLine "LastWriteTime Attribute: $($Item.LastWriteTime)" #Loop for Item to check if its read- and writeable. DO { $FileCheckCounter++ Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "This ist Try Number: $FileCheckCounter of $FileCheckCounterLimit" Func-Write-Logfile -LogLine "to handle file: $Item" IF ($filechecktyp -match "write") { Write-Host "DEBUG Info: writetest will be done..." $FileCheckResult = (Func-File-check-state -FilePath_and_FileName $Item -filechecktyp write) } #end if ELSE { Write-Host "DEBUG Info: Only a readtest will be done" $FileCheckResult = (Func-File-check-state -FilePath_and_FileName $Item -filechecktyp read) } #end else } #end do UNTIL (($filecheckresult -eq "readable" -or $filecheckresult -eq "writeable") -or ($FileCheckResult -eq "unavailable") -or ($FileCheckCounter -eq $FileCheckCounterLimit) -or ($FileCheckCounter -gt $FileCheckCounterLimit)) #If Item is not read- and writeable, skip it! IF (($FileCheckCounter -eq $FileCheckCounterLimit) -or ($FileCheckCounter -gt $FileCheckCounterLimit) -or ($FileCheckResult -eq "unavailable")) { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Skipping file: $item," Func-Write-Logfile -LogLine "because Limit of attemts has been exeeded, or File is not available anymore!" Func-Write-Logfile -LogLine "-> Try: $FileCheckCounter of $FileCheckCounterLimit" } #end if #If Item is read- and writeable... what are you waiting for? Do your work! Damn piece of s%$!! ELSE { #For every File / loop this var mus be determinated new because path can include file attibut vars like CreationTime $DestinationPath = $DestinationPathTemplate #------------------------------------ Code block for the ItemCreationTime Vars ------------------------------------- [String]$ItemCreationTime = $NULL [String]$ItemCreationTime = $($Item.CreationTime) IF ($ItemCreationTime -gt $NULL) { [String]$ItemCreationTime = $ItemCreationTime.Split(" ")[0] [String]$ItemCreationTimeYear = $ItemCreationTime.Split($DateSeperator)[2] [String]$ItemCreationTimeMonth = $ItemCreationTime.Split($DateSeperator)[0] [String]$ItemCreationTimeDay = $ItemCreationTime.Split($DateSeperator)[1] IF ($DestinationPathTemplate -match "%CreationTimeYear%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%CreationTimeYear%'})) [String]$DestinationPath = ($DestinationPath -replace('%CreationTimeYear%',($ItemCreationTimeYear))) Write-Host "DEBUG Info: ItemCreationTimeYear: $ItemCreationTimeYear)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%CreationTimeMonth%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%CreationTimeMonth%'})) [String]$DestinationPath = ($DestinationPath -replace('%CreationTimeMonth%',($ItemCreationTimeMonth))) Write-Host "DEBUG Info: ItemCreationTimeMonth: $ItemCreationTimeMonth)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%CreationTimeDay%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%CreationTimeDay%'})) [String]$DestinationPath = ($DestinationPath -replace('%CreationTimeDay%',($ItemCreationTimeDay))) Write-Host "DEBUG Info: ItemCreationTimeDay: $ItemCreationTimeDay)" } #end if Write-Host "DEBUG Info: $DestinationPath" } #end if #--------------------------------------------------------------------------------------------------------------------- #------------------------------------ Code block for the ItemLastAccessTime Vars ------------------------------------- [String]$ItemLastAccessTime = $NULL [String]$ItemLastAccessTime = $($Item.LastAccessTime) IF ($ItemLastAccessTime -gt $NULL) { [String]$ItemLastAccessTime = $ItemLastAccessTime.Split(" ")[0] [String]$ItemLastAccessTimeYear = $ItemLastAccessTime.Split($DateSeperator)[2] [String]$ItemLastAccessTimeMonth = $ItemLastAccessTime.Split($DateSeperator)[0] [String]$ItemLastAccessTimeDay = $ItemLastAccessTime.Split($DateSeperator)[1] IF ($DestinationPath -match "%LastAccessTimeYear%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastAccessTimeYear%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastAccessTimeYear%',($ItemLastAccessTimeYear))) Write-Host "DEBUG Info: ItemLastAccessTimeYear: $ItemLastAccessTimeYear)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%LastAccessTimeMonth%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastAccessTimeMonth%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastAccessTimeMonth%',($ItemLastAccessTimeMonth))) Write-Host "DEBUG Info: ItemLastAccessTimeMonth: $ItemLastAccessTimeMonth)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%LastAccessTimeDay%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastAccessTimeDay%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastAccessTimeDay%',($ItemLastAccessTimeDay))) Write-Host "DEBUG Info: ItemLastAccessTimeDay: $ItemLastAccessTimeDay)" } #end if Write-Host "DEBUG Info: $DestinationPath" } #end if #--------------------------------------------------------------------------------------------------------------------- #------------------------------------ Code block for the ItemLastWriteTime Vars ------------------------------------- [String]$ItemLastWriteTime = $NULL [String]$ItemLastWriteTime = $($Item.LastWriteTime) IF ($ItemLastWriteTime -gt $NULL) { [String]$ItemLastWriteTime = $ItemLastWriteTime.Split(" ")[0] [String]$ItemLastWriteTimeYear = $ItemLastWriteTime.Split($DateSeperator)[2] [String]$ItemLastWriteTimeMonth = $ItemLastWriteTime.Split($DateSeperator)[0] [String]$ItemLastWriteTimeDay = $ItemLastWriteTime.Split($DateSeperator)[1] IF ($DestinationPath -match "%LastWriteTimeYear%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastWriteTimeYear%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastWriteTimeYear%',($ItemLastWriteTimeYear))) Write-Host "DEBUG Info: ItemLastWriteTimeYear: $ItemLastWriteTimeYear)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%LastWriteTimeMonth%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastWriteTimeMonth%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastWriteTimeMonth%',($ItemLastWriteTimeMonth))) Write-Host "DEBUG Info: ItemLastWriteTimeMonth: $ItemLastWriteTimeMonth)" } #end if Write-Host "DEBUG Info: $DestinationPath" IF ($DestinationPath -match "%LastWriteTimeDay%") { [String]$DestinationPath = ($DestinationPath | Where({$_ -match '%LastWriteTimeDay%'})) [String]$DestinationPath = ($DestinationPath -replace('%LastWriteTimeDay%',($ItemLastWriteTimeDay))) Write-Host "DEBUG Info: ItemLastWriteTimeDay: $ItemLastWriteTimeDay)" } #end if Write-Host "DEBUG Info: $DestinationPath" } #end if #--------------------------------------------------------------------------------------------------------------------- #Differ if a RegEx is set or not IF (($RegExGroupIndex -gt $NULL) -and ($RegExGroup -gt $NULL)) { Write-Host "DEBUG Info - RegEx: Is set!" $RegExResult = ([regex]::Match("$Item", "$RegExGroup").Groups[$RegExGroupIndex].Value) Func-Path-Check -Path $DestinationPath\$RegExResult #Is a Replace set? IF ($Replace -gt $NULL) { Write-Host "DEBUG Info - Replace: Is set!" Set-Variable -Name ItemMoved -Value (Move-or-Copy-Item-withLogging -FilePath_and_FileName "$Item" -DestinationPath $DestinationPath\$RegExResult -move_or_copy $MoveOrCopy -NewfileName (($Item.BaseName).Replace($Replace[0],$Replace[1]))) -Scope Script } #end if ELSE { Write-Host "DEBUG Info - Replace: Is not set!" Set-Variable -Name ItemMoved -Value (Move-or-Copy-Item-withLogging -FilePath_and_FileName "$Item" -DestinationPath $DestinationPath\$RegExResult -move_or_copy $MoveOrCopy) -Scope Script } #end else } #end if ELSE { Write-Host "DEBUG Info - RegEx: Is not set!" Func-Path-Check -Path $DestinationPath #Is a Replace set? IF ($Replace -gt $NULL) { Write-Host "DEBUG Info - Replace: Is set!" Set-Variable -Name ItemMoved -Value (Move-or-Copy-Item-withLogging -FilePath_and_FileName "$Item" -DestinationPath $DestinationPath -move_or_copy $MoveOrCopy -NewfileName (($Item.BaseName).Replace($Replace[0],$Replace[1]))) -Scope Script } #end if ELSE { Write-Host "DEBUG Info - Replace: Is not set!" Set-Variable -Name ItemMoved -Value (Move-or-Copy-Item-withLogging -FilePath_and_FileName "$Item" -DestinationPath $DestinationPath -move_or_copy $MoveOrCopy) -Scope Script } #end else } #end else #Adding Values in every foreach run - into dynamic array for later processing Write-Host "DEBUG Info - ItemMoved: $ItemMoved" $ItemsMoved.Add($ItemMoved) #Resetting counter, because everything seems to be fine. Set-Variable -Name FileCheckCounter -Value $NULL -Scope Script } #end else } #end foreach IF ($SourcePath -contains "%ProcessOnlyLastProfileFiles") { #Reset for next profile run $ItemsMoved = $NULL $ItemMoved = $NULL $Items = $NULL $Item = $NULL } #end if } #end if ELSE { Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "WARNING: Found no valid Files for processing!" Func-Write-Logfile -LogLine "INFO: Please check your filter Settings." } #end else Func-Write-Logfile -LogLine "===========================================================================================" } #end foreach } #end if ELSE { Func-Write-Logfile -LogLine "There is/are no Profile(s) to process." } #end else #-----------------------------------------------------------------------------------------------------# ########################################### finishing part ############################################ #-----------------------------------------------------------------------------------------------------# #Delete old LogFiles, depending on Variable $LogFileKeepTime. Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" Func-Write-Logfile -LogLine "Checking LogFiles:" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" IF ($LogFileKeepTime -gt 0) { Func-Write-Logfile -LogLine "Log Files should be removed which are older than $LogFileKeepTime Day(s)." #Set-Variable -Name Items -Value (Func-File-Collector -SearchPath "$LogPath\*" -SearchWhiteList *.log | where {$_.Name -like "*$ScriptName*" -and $_.lastwritetime -lt $((Get-Date).AddDays(-$LogFileKeepTime)) -and -not $_.psiscontainer}) Set-Variable -Name Items -Value (Get-ChildItem -Path "$LogPath\*" -Filter *.log | where {$_.Name -like "*$ScriptName*" -and $_.CreationTime -lt $((Get-Date).AddDays(-$LogFileKeepTime)) -and -not $_.psiscontainer}) IF ($Items -eq $null) { Func-Write-Logfile -LogLine "Deleting no old LogFiles." } #end if ELSE { Func-Write-Logfile -LogLine "Found $($Items.count) old log files." Func-Write-Logfile -LogLine "Deleting old LogFiles..." FOREACH ($Item in $Items) { Try { Remove-Item -Path $Item.FullName -Force -Verbose #Func-Write-Logfile -LogLine "LogFile: $Item was removed." } #end try Catch { Func-Write-Logfile -LogLine "LogFile: $($Item.FullName) cannot been removed." Func-Write-Logfile -LogLine "Please check your privileges!" } #end catch } #end foreach } # end else } #end if ELSE { Func-Write-Logfile -LogLine "You disabled LogFile deleting in ConfigFile, they all will be kept." } #end else Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "*******************************************************************************************" Func-Write-Logfile -LogLine "Program Finish: $ScriptName on $env:computername from Account $env:USERDOMAIN\$env:USERNAME." Func-Write-Logfile -LogLine "*******************************************************************************************" #Delete Variables used by this Script, to clean up the RAM. Remove-Variable -Name argOperation -ErrorAction SilentlyContinue Remove-Variable -Name argFileTypes -ErrorAction SilentlyContinue Remove-Variable -Name argSourcePath -ErrorAction SilentlyContinue Remove-Variable -Name argDestinationPath -ErrorAction SilentlyContinue Remove-Variable -Name argFileDelayAge -ErrorAction SilentlyContinue Remove-Variable -Name ScriptName -ErrorAction SilentlyContinue Remove-Variable -Name ScriptPath -ErrorAction SilentlyContinue Remove-Variable -Name ConfigFile -ErrorAction SilentlyContinue Remove-Variable -Name KonfigWerte -ErrorAction SilentlyContinue Remove-Variable -Name ZeitStempel1 -ErrorAction SilentlyContinue Remove-Variable -Name Fehler -ErrorAction SilentlyContinue Remove-Variable -Name LogDatei -ErrorAction SilentlyContinue Remove-Variable -Name LogLine -ErrorAction SilentlyContinue Remove-Variable -Name LogPathListe -ErrorAction SilentlyContinue Remove-Variable -Name LogPath -ErrorAction SilentlyContinue Remove-Variable -Name LogPathEintrag -ErrorAction SilentlyContinue Remove-Variable -Name LogFileKeepTime -ErrorAction SilentlyContinue Remove-Variable -Name FileDelayAge -ErrorAction SilentlyContinue Remove-Variable -Name Item -ErrorAction SilentlyContinue Remove-Variable -Name ItemMoved -ErrorAction SilentlyContinue Remove-Variable -Name Items -ErrorAction SilentlyContinue Remove-Variable -Name ItemsMoved -ErrorAction SilentlyContinue Remove-Variable -Name Path -ErrorAction SilentlyContinue Remove-Variable -Name PathTest -ErrorAction SilentlyContinue Remove-Variable -Name ProzessTest -ErrorAction SilentlyContinue Remove-Variable -Name VersionSeperator -ErrorAction SilentlyContinue Remove-Variable -Name Counter -ErrorAction SilentlyContinue Remove-Variable -Name FileTypes -ErrorAction SilentlyContinue Remove-Variable -Name FileCheckResult -ErrorAction SilentlyContinue Remove-Variable -Name FileWhiteList -ErrorAction SilentlyContinue Remove-Variable -Name FileBlackList -ErrorAction SilentlyContinue Remove-Variable -Name FileSeperator -ErrorAction SilentlyContinue Remove-Variable -Name FileCheckCounter -ErrorAction SilentlyContinue Remove-Variable -Name FileCheckCounterLimit -ErrorAction SilentlyContinue Remove-Variable -Name MoveOrCopy -ErrorAction SilentlyContinue Remove-Variable -Name SourcePath -ErrorAction SilentlyContinue Remove-Variable -Name DestinationPathTemplate -ErrorAction SilentlyContinue Remove-Variable -Name DestinationPath -ErrorAction SilentlyContinue Remove-Variable -Name MinimumNumOfParams -ErrorAction SilentlyContinue Remove-Variable -Name RegExGroup -ErrorAction SilentlyContinue Remove-Variable -Name RegExGroupIndex -ErrorAction SilentlyContinue Remove-Variable -Name RegExResult -ErrorAction SilentlyContinue Remove-Variable -Name Replace -ErrorAction SilentlyContinue Remove-Variable -Name DateSeperator -ErrorAction SilentlyContinue Remove-Variable -Name ItemCreationTime -ErrorAction SilentlyContinue Remove-Variable -Name ItemCreationTimeYear -ErrorAction SilentlyContinue Remove-Variable -Name ItemCreationTimeMonth -ErrorAction SilentlyContinue Remove-Variable -Name ItemCreationTimeDay -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastAccessTime -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastAccessTimeYear -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastAccessTimeMonth -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastAccessTimeDay -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastWriteTime -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastWriteTimeYear -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastWriteTimeMonth -ErrorAction SilentlyContinue Remove-Variable -Name ItemLastWriteTimeDay -ErrorAction SilentlyContinue Remove-Variable -Name FileCheckTyp -ErrorAction SilentlyContinue Remove-Variable -Name MOCF_Profile* -ErrorAction SilentlyContinue $error.clear()