# PowerShell 4.0 Script # Script for handeling rejected files, with SQL-DB support # Digital Data # Ludwig-Rinn-Strasse 16 # 35452 Heuchelheim # Tel.: 0641 / 202360 # E-Mail: info@didalog.de # Version Number: 1.0.0.0 Pre-Release # Version Date: 30.09.2015 # 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 # Microsoft SQL Client is needed! # 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 #-----------------------------------------------------------------------------------------------------# ###################################### add additional assemblys ####################################### #-----------------------------------------------------------------------------------------------------# #-----------------------------------------------------------------------------------------------------# ############################################ 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 (Get-ChildItem -Path "$ScriptPath" -Recurse -Filter "$ScriptName`_Settings.ini" -File -Force).FullName -Scope script Set-Variable -Name ConfigValues -Value $NULL -Scope script Set-Variable -Name Timestamp1 -Value $(Get-Date -Format 'ddMMyyyy') -Scope script Set-Variable -Name Timestamp2 -Value $(Get-Date -Format 'ddMMyyyy_HHmmss') -Scope script Set-Variable -Name Timestamp3 -Value $(Get-Date -Format 'ddMMyyyy_HHmmssffff') -Scope script Set-Variable -Name Timestamp4 -Value $(Get-Date -Format 'yyyyMMdd HH:mm:ss.fff') -Scope script Set-Variable -Name LogFile -Value "$ScriptName`_$Timestamp2.log" -Scope script Set-Variable -Name LogFileKeepTime -Value 90 -Scope script Set-Variable -Name LogLine -Value $NULL -Scope local Set-Variable -Name LogPath -Value $NULL -Scope script Set-Variable -Name LogPathError -Value $NULL -Scope local Set-Variable -Name LogPathValue -Value $NULL -Scope script Set-Variable -Name LogPathValues -Value $NULL -Scope script Set-Variable -Name FileDelayAge -Value 5 -Scope script Set-Variable -Name FilePath_and_FileName -Value $NULL -Scope local Set-Variable -Name FileCheckResult -Value $NULL -Scope local Set-Variable -Name SourcePathSplit -Value $NULL -Scope script Set-Variable -Name Item -Value $NULL -Scope local Set-Variable -Name Items -Value $NULL -Scope local Set-Variable -Name Path -Value $NULL -Scope local Set-Variable -Name PathTest -Value $NULL -Scope local Set-Variable -Name VersionSeperator -Value '~' -Scope script Set-Variable -Name FileSeperator -Value '_' -Scope script Set-Variable -Name Counter -Value $NULL -Scope local Set-Variable -Name FileName -Value $NULL -Scope local Set-Variable -Name FileName_noExt -Value $NULL -Scope local Set-Variable -Name FileHash -Value $NULL -Scope local Set-Variable -Name FileQuery -Value $NULL -Scope local Set-Variable -Name FileQuery_Limit -Value $NULL -Scope local Set-Variable -Name filestream -Value $NULL -Scope local Set-Variable -Name SourcePath -Value $NULL -Scope local Set-Variable -Name Destinationpath -Value $NULL -Scope local Set-Variable -Name newfilename -Value $NULL -Scope local Set-Variable -Name newfilenamelength -Value $NULL -Scope local Set-Variable -Name DBSQLDataSet -Value $NULL -Scope script Set-Variable -Name DBSQLQuery -Value $NULL -Scope script Set-Variable -Name DBSQLCommand -Value $NULL -Scope script Set-Variable -Name DBSQLAdapter -Value $NULL -Scope script Set-Variable -Name DBSQLConnection -Value $NULL -Scope script Set-Variable -Name DBSQLConnectServer -Value $NULL -Scope script Set-Variable -Name DBSQLConnectUser -Value $NULL -Scope script Set-Variable -Name DBSQLConnectPassword -Value $NULL -Scope script Set-Variable -Name DBSQLConnectDatabase -Value $NULL -Scope script Set-Variable -Name DBSQLConnectIntegratedSecurity -Value $NULL -Scope script Set-Variable -Name DBSQLErrorAction -Value 'continue' -Scope script Set-Variable -Name DBSQL_NewFilename -Value $NULL -Scope script #-----------------------------------------------------------------------------------------------------# ############################################ set functions ############################################ #-----------------------------------------------------------------------------------------------------# Function Func-Path-Check { <# .SYNOPSIS Function will check the given Path for existence. .DESCRIPTION Function will check the given Path for existence. If Path doesn´t exist, Function will try to create it. .REQUIREMENT General PowerShell V2 and Function "Func-Write-Logfile". .REQUIREMENT Variables Path, PathTest .REQUIREMENT Functions - .VERSION Number: 1.0.0.0 / Date: 23.09.2015 .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 ) Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Checking Path $Path for existence." $PathTest = Test-Path -PathType Container $Path IF ($PathTest -eq "True") { Func-Write-Logfile -LogLine "Path $Path already exists and can be used." } #end if ELSE { Try { Func-Write-Logfile -LogLine "Path $Path has to been created." New-Item -Path $Path -ItemType directory -force -ErrorAction Stop } #end try 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 catch } #end else } #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 LogPathValues, LogPathValue, LogPath, LogFile, LogPathError, Pfad-Test .REQUIREMENT Functions Func-Path-Check .VERSION Number: 1.0.0.0 / Date: 23.09.2015 .EXAMPLE Func-Path-Check -LogLine "Write this in my Log, please." .EXAMPLE Func-Path-Check -LogLine "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 LogPathError -Value 1 } #end if ELSE { Set-Variable -Name LogPathError -Value $NULL } #end else IF ($LogPath -eq $NULL) { IF ($LogPathValues -gt ' ') { Set-Variable -Name LogPathValues -Value @($LogPathValues) Set-Variable -Name LogPathValues -Value ($LogPathValues += "$ScriptPath\Logs","$env:temp\Digital Data\$ScriptName\Logs") -Scope script Write-Host "DEBUG Info: LogPathValues: $LogPathValues" } #end if ELSE { #Set-Variable -Name LogPathValues -Value @() Set-Variable -Name LogPathValues -Value @("$ScriptPath\Logs","$env:temp\Digital Data\$ScriptName\Logs") -Scope script Write-Host "DEBUG Info: LogPathValues: $LogPathValues" } #end else FOREACH ($LogPathValue in $LogPathValues) { $PathTest = Test-Path -PathType Container "$LogPathValue" Write-Host "DEBUG Info: Pfadüberprüfung: Prüfe ob LogPath bereits angelegt ist: $LogPathValue" IF ($PathTest -eq "True") { Write-Host "DEBUG Info: Pfadüberprüfung: LogPath $LogPathValue ist bereits angelegt!" Set-Variable -Name LogPath -Value $LogPathValue break } #end if ELSE { Write-Host "DEBUG Info: Pfadüberprüfung: LogPath $LogPathValue muss angelegt werden." New-Item -Path $LogPathValue -ItemType directory -force -ErrorAction SilentlyContinue | Out-Null $PathTest = Test-Path -PathType Container $LogPathValue Write-Host "DEBUG Info: Pfadüberprüfung: Prüfe ob Pfad erfolgreich angelegt werden konnte." IF ($PathTest -eq "True") { Write-Host "DEBUG Info: Pfadüberprüfung: Pfad $LogPathValue wurde erfolgreich angelegt." Set-Variable -Name LogPath -Value $LogPathValue break } #end if ELSE { Write-Host "DEBUG Info: Pfadüberprüfung: Pfad $LogPathValue konnte nicht angelegt werden." Set-Variable -Name LogPath -Value $LogPathValue } #end else } #end else } #end foreach } #end if ELSEIF ($LogPath -eq "$env:temp\Digital Data\$ScriptName\Logs") { Write-Warning "FEHLER: LogPath nicht zugreifbar oder nicht korrekt konfiguriert!" Write-Warning "INFO: $LogPath - wird nun verwendet!" Write-Warning "Programm wird trotzdem fortgesetzt." } # Setze Variable nun "Skriptweit" Set-Variable -Name LogPath -Value $LogPath -scope script Write-Host $LogLine Add-content $LogPath\$LogFile -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): $LogLine" IF ($LogPathError -eq 1) { Write-Host "DEBUG Info: Error Message(s): $error" Add-content $LogPath\$LogFile -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): Error Message(s): $error" # Setze Fehlerspeicher zurück $error.clear() } #end if } #end function Function Func-Read-ConfigFile { <# .SYNOPSIS Function will read the given ConfigFile. .DESCRIPTION Function will write a given String to a Logfile. It will even log Error Messages. .REQUIREMENT General PowerShell V2 .REQUIREMENT Variables LogPathValues, LogPathValue, LogPath, LogFile, LogPathError, Pfad-Test .REQUIREMENT Functions .VERSION Number: 1.0.0.0 / Date: 23.09.2015 .EXAMPLE Func-Path-Check -LogLine "Write this in my Log, please." .EXAMPLE Func-Path-Check -LogLine "Write this Variabel $Variable in my Log, please." .PARAMETER ConfigFile Give the full path to the ConfigFile. #> 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 "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 ConfigValues -Value (Select-String -path $ConfigFile -pattern "=" | where {-not($_-match "#")}) IF ($ConfigValues -eq $Null) { Write-Host "Keine gültigen Werte in Konfigurationsdatei erkannt!" } ELSE { Write-Host "Es wurden"$ConfigValues.count"Zeilen aus der Konfigurationsdatei eingelesen." # Write-Host "Folgende Werte wurden eingelesen:" # Write-Host "$ConfigValues" } Set-Variable -Name ConfigValues -Value $ConfigValues -Scope script } #end function Function Func-Read-ConfigValue { <# .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.0.0.0 / Date: 23.09.2015 .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. #> # Funktion um eine Textdatei (ASCII), komplett einzulesen. # Gibt immer nur einen Wert zurück! Param ( [String]$ConfigLabel ) $Items = ($ConfigValues.line | select-string -pattern "$ConfigLabel") IF ($Items -eq $NULL) { Write-Host "Der gesuchte Bezeichner ($ConfigLabel) konnte nicht gefunden werden!" Write-Host "Standardwert wird verwendet!" $ConfigLabel = (Get-Variable -Name $ConfigLabel -ValueOnly) return $ConfigLabel } 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.0.0.0 / Date: 23.09.2015 .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 ) 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 ";") $Items = Get-ChildItem -Path "$SearchPath" -include $SearchWhiteList -exclude $SearchBlackList -Recurse 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) 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-copy-or-move { <# .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 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.0.0 / Date: 23.09.2015 .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 $filestream.Close() Set-Variable -Name filecheckresult -Value "readable" } #end try catch { Func-Write-Logfile -LogLine "File: $FilePath_and_FileName is not even readable." Write-Host "DEBUG Info: Is file readable?" $filestream.CanRead 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 $filestream.Close() Set-Variable -Name filecheckresult -Value "writeable" } #end try Catch { Func-Write-Logfile -LogLine "File: $FilePath_and_FileName is not writeable." Write-Host "DEBUG Info: Is file writeable?" $filestream.CanWrite 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." } #end else } #end function Function Func-DB-SQL-Query { <# .SYNOPSIS Function will send a SQL Query to a SQL DB. .DESCRIPTION Function will send a SQL Query to a SQL DB. If you set a read command (SELECT ...), function will return a dataset. .REQUIREMENT General PowerShell V2 and Function "Func-Write-Logfile". .REQUIREMENT Variables DBSQLQuery, DBSQLQueryType, DBSQLConnectServer, DBSQLConnectUser, DBSQLConnectPassword, DBSQLConnectDatabase, DBSQLConnectIntegratedSecurity, DBSQLCommand, DBSQLAdapter, DBSQLConnection .REQUIREMENT Functions Func-Write-Logfile .VERSION Number: 1.0.0.0 / Date: 23.09.2015 .EXAMPLE Func-DB-SQL-Query -DBSQLQueryType read -DBSQLQuery "SELECT * from TABLE;" .EXAMPLE Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "INSERT INTO TABLE (column1,column2,column3) VALUES ('Text1', Zahl1, Zahl2) WHERE column4 = 'Text2';" .EXAMPLE Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "UPDATE TABLE SET column1='Text1',column2=Zahl1,column3=Zahl2 WHERE column4 = 'Text2';" .PARAMETER DBSQLQuery Give a Standard T-SQL Query .PARAMETER DBSQLQueryType Give read or write, depends on your planned action ("select" is only read, "insert" and "update" are write) #> Param ( [String]$DBSQLQuery, [String]$DBSQLQueryType, [String]$DBSQLErrorAction ) Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "Connecting with DB:" Func-Write-Logfile -LogLine "Server = $DBSQLConnectServer, uid=$DBSQLConnectUser, pwd=, Database = $DBSQLConnectDatabase, Integrated Security = $DBSQLConnectIntegratedSecurity" IF (($DBSQLQueryType -eq 'read') -or ($DBSQLQueryType -eq 'write')) { Try { $DBSQLConnection = New-Object System.Data.SqlClient.SqlConnection $DBSQLConnection.ConnectionString = "Server = $DBSQLConnectServer; ;uid=$DBSQLConnectUser; pwd=$DBSQLConnectPassword; Database = $DBSQLConnectDatabase; Integrated Security = $DBSQLConnectIntegratedSecurity" Func-Write-Logfile -LogLine "Processing SQL Query:" Func-Write-Logfile -LogLine $DBSQLQuery IF ($DBSQLQueryType -eq 'read') { Try { $DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand $DBSQLCommand.CommandText = $DBSQLQuery $DBSQLCommand.Connection = $DBSQLConnection $DBSQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $DBSQLAdapter.SelectCommand = $DBSQLCommand $DBSQLDataSet = New-Object System.Data.DataSet $DBSQLConnection.Open() $DBSQLAdapter.Fill($DBSQLDataSet) $DBSQLConnection.Close() Func-Write-Logfile -Logline "SQL Query result with $($DBSQLDataSet.Tables[0].Rows.Count) row(s)." #$DBSQLDataSet.Tables[0].Rows | Out-GridView Return $DBSQLDataSet } #end try Catch { Func-Write-Logfile -LogLine "ERROR: Unable to process SQL Query (read)!" IF ($ErrorAction -eq 'continue') { Func-Write-Logfile -LogLine "Program will continue, anyway." } #end if ELSEIF ($ErrorAction -eq 'stop') { Func-Write-Logfile -LogLine "Program will stop." exit } #end elseif ELSE { Func-Write-Logfile -LogLine "Invalid Value for Parameter DBSQLErrorAction detected." Func-Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'." Func-Write-Logfile -LogLine "Program will continue, anyway." } #end else } #end catch } #end if ELSEIF ($DBSQLQueryType -eq 'write') { Try { $DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand $DBSQLCommand.CommandText = $DBSQLQuery $DBSQLCommand.Connection = $DBSQLConnection $DBSQLConnection.Open() $DBSQLCommand.ExecuteNonQuery() $DBSQLConnection.Close() } #end try Catch { Func-Write-Logfile -LogLine "ERROR: Unable to process SQL Query (write)!" IF ($ErrorAction -eq 'continue') { Func-Write-Logfile -LogLine "Program will continue, anyway." } #end if ELSEIF ($ErrorAction -eq 'stop') { Func-Write-Logfile -LogLine "Program will stop." exit } #end elseif ELSE { Func-Write-Logfile -LogLine "Invalid Value for parameter DBSQLErrorAction detected." Func-Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'." Func-Write-Logfile -LogLine "Program will continue, anyway." } #end else } #end catch } #end elseif ELSE { Func-Write-Logfile -LogLine "ERROR: Invalid parameter for function!" } #end else } #end try Catch { Func-Write-Logfile -LogLine "ERROR: Unable to etablish a DB Connection!" } #end catch } #end if ELSE { Func-Write-Logfile -LogLine "Only read or write is valid for $DBSQLQueryType!" } #end else } #end function #-----------------------------------------------------------------------------------------------------# ########################################### preparing part ############################################ #-----------------------------------------------------------------------------------------------------# #Clear Console Window Clear-Host #Read ConfigValues from ConfigFile Func-Read-ConfigFile -ConfigFile $ConfigFile #Read each ConfigValue from ConfigValues Set-Variable -Name LogPathValues -Value (Func-Read-ConfigValue -ConfigLabel LogPathValue) Set-Variable -Name LogFileKeepTime -Value (Func-Read-ConfigValue -ConfigLabel LogFileKeepTime) Set-Variable -Name FileDelayAge -Value (Func-Read-ConfigValue -ConfigLabel FileDelayAge) Set-Variable -Name FileSeperator -Value (Func-Read-ConfigValue -ConfigLabel FileSeperator) Set-Variable -Name VersionSeperator -Value (Func-Read-ConfigValue -ConfigLabel VersionSeperator) Set-Variable -Name FileNameConstructor -Value (Func-Read-ConfigValue -ConfigLabel FileNameConstructor) Set-Variable -Name DBSQLConnectServer -Value (Func-Read-ConfigValue -ConfigLabel DBSQLConnectServer) Set-Variable -Name DBSQLConnectUser -Value (Func-Read-ConfigValue -ConfigLabel DBSQLConnectUser) Set-Variable -Name DBSQLConnectPassword -Value (Func-Read-ConfigValue -ConfigLabel DBSQLConnectPassword) Set-Variable -Name DBSQLConnectDatabase -Value (Func-Read-ConfigValue -ConfigLabel DBSQLConnectDatabase) Set-Variable -Name DBSQLConnectIntegratedSecurity -Value (Func-Read-ConfigValue -ConfigLabel DBSQLConnectIntegratedSecurity) Set-Variable -Name DBSQLErrorAction -Value (Func-Read-ConfigValue -ConfigLabel DBSQLErrorAction) Set-Variable -Name feh_rulelist -Value (Func-Read-ConfigValue -ConfigLabel feh_rule??) FOREACH ($feh_rule in $feh_rulelist) { Write-Host "" Write-Host "DEBUG Info: Folgende Zeilen wurden ausgelesen: --> $feh_rule <--" $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 ($feh_rule -is [String]) { $feh_rule = @($feh_rule) $feh_rule = ($feh_rule -split ";") #$feh_rule = ($feh_rule -split ",") } #end if ELSE { $feh_rule = @($feh_rule) $feh_rule = ($feh_rule -Split "=" ) $feh_rule = ($feh_rule[1]) $feh_rule = ($feh_rule -split ";") #$feh_rule = ($feh_rule -split ",") } #end else [System.Collections.ArrayList]$feh_rulevalues = @() # Split an merge Array to remove blanks FOREACH ($feh_rulevalue in $feh_rule) { $feh_rulevalue = ($feh_rulevalue.TrimStart()) $feh_rulevalue = ($feh_rulevalue.TrimEnd()) $feh_rulevalues.Add($feh_rulevalue) } #end foreach IF ($feh_rulevalues -eq $NULL) { Write-Host "DEBUG Info: Der erwarteter Wert ist leer!" Write-Host "DEBUG Info: Standardwert wird eingetragen!" Set-Variable -Name ("feh_rule"+$Counter) -value "Standard" -Scope script } #end if ELSE { Write-Host DEBUG Info: ("feh_rule"+$Counter) wurde als Variable gesetzt und hat folgende Werte bekommen: $feh_rulevalues Set-Variable -Name ("feh_rule"+$Counter) -value $feh_rulevalues -Scope script } #end else } #end foreach #-----------------------------------------------------------------------------------------------------# ############################################# main part ############################################### #-----------------------------------------------------------------------------------------------------# Write-Host "" Func-Write-Logfile -LogLine "*******************************************************************************************" Func-Write-Logfile -LogLine "Program Startup: $ScriptName on $env:computername from Account $env:USERDOMAIN\$env:USERNAME." Func-Write-Logfile -LogLine "*******************************************************************************************" IF ($($feh_rulelist.count) -gt 0) { Func-Write-Logfile -LogLine "There is/are $($feh_rulelist.count) out of 99 Rule(s) to process, starting now." #Reset counter Set-Variable -Name Counter -Value $NULL #Loop for each rule FOREACH ($feh_rule in $(get-variable -Name feh_rule??)) { $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 ("feh_rule"+$Counter)).name) now." Func-Write-Logfile -LogLine "===========================================================================================" Func-Write-Logfile -LogLine "" Func-Write-Logfile -LogLine "These Values are setup: $(Get-Variable -Name ("feh_rule"+$Counter) -ValueOnly)." # Save all given parameters of this profile. Set-Variable -Name feh_rulevalues -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly) -Scope local # Save the first array value in the given parameters of this profile. Set-Variable -Name FileTyps -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly)[0] -Scope local # Save the second array value in the given parameters of this profile. Set-Variable -Name SourcePath -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly)[1] -Scope local # Save the third array value in the given parameters of this profile. Set-Variable -Name DestinationPath -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly)[2] -Scope local # Save the fourth array value in the given parameters of this profile. Set-Variable -Name EscalationPath -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly)[3] -Scope local # Save the fifth array value in the given parameters of this profile. Set-Variable -Name FileQuery_Limit -Value $(get-variable -name ("feh_rule"+$Counter) -ValueOnly)[4] -Scope local $FileQuery_Limit = $FileQuery_Limit -as [Int] # If more than five parameters are given, check optional parameters. IF ($(Get-Variable -Name ("feh_rule"+$Counter) -ValueOnly).count -gt 5) { # Set value for date if given in the parameters. IF ($(Get-Variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%date") { Set-Variable -Name newfilename -Value ($Timestamp1+$FileSeperator) } #end if ELSEIF ($(Get-Variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%datetime") { Set-Variable -Name newfilename -Value ($Timestamp2+$FileSeperator) } #end elseif ELSEIF ($(Get-Variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%datetime2") { Set-Variable -Name newfilename -Value ($Timestamp3+$FileSeperator) } #end elseif # Set value for sourcepath if given in the parameters. IF ($(get-variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%sourcefolder") { Set-Variable -Name SourcePathSplit -Value ($SourcePath -split "\\") Set-Variable -Name SourcePathSplit -Value ($SourcePathSplit[-1]) Set-Variable -Name newfilename -Value ($newfilename+$SourcePathSplit+$FileSeperator) } #end if ELSEIF ($(get-variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%sourcefolder2") { Set-Variable -Name SourcePathSplit -Value ($SourcePath -split "\\") Set-Variable -Name SourcePathSplit -Value ($SourcePathSplit[-2]) Set-Variable -Name newfilename -Value ($newfilename+$SourcePathSplit+$FileSeperator) } #end elseif ELSEIF ($(get-variable -Name ("feh_rule"+$Counter) -ValueOnly) -contains "%sourcefolder3") { Set-Variable -Name SourcePathSplit -Value ($SourcePath -split "\\") Set-Variable -Name SourcePathSplit -Value ($SourcePathSplit[-3]) Set-Variable -Name newfilename -Value ($newfilename+$SourcePathSplit+$FileSeperator) } #end elseif # Set value for static text if given in the parameters. IF ($(get-variable -name ("feh_rule"+$Counter) -ValueOnly) -like "%%*%%") { Set-Variable -Name statictext -Value ((($(get-variable -name ("feh_rule"+$Counter) -ValueOnly) -like "%%*%%") | Where-Object {$_ –like "%%*%%"}).ToString()).Replace("%%",'') Set-Variable -Name newfilename -Value ($newfilename+$statictext+$FileSeperator) } #end if ELSE { Set-Variable -Name statictext -value $NULL } #end else } #end if Func-Write-Logfile -LogLine "This run, searches for files in folder: $SourcePath" Set-Variable -Name Items -Value (Func-File-Collector -SearchPath $SourcePath -SearchWhiteList $filetyps | where-object {$_.lastwritetime -lt (get-date).addminutes(-$FileDelayAge)}) #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 "-------------------------------------------------------------------------------------------" Set-Variable -Name FileHash -Value (Get-FileHash -Path "$($Item.FullName)" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""}) Write-Host "DEBUG Info: Filehash: $FileHash" $DBSQLDataSet.clear Set-Variable -Name DBSQLDataSet -Value (Func-DB-SQL-Query -DBSQLQueryType read -DBSQLErrorAction stop -DBSQLQuery "SELECT DISTINCT * FROM TBDD_LURATECH_ERROR WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash'") #$DBSQLDataSet.Tables[0].rows | Out-GridView #If there are rows in DB for this file. IF ($($DBSQLDataSet.Tables[0].Rows.Count) -gt 0) { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] Func-Write-Logfile -LogLine "File: $Item already exits in SQL Table TBDD_LURATECH_ERROR - current FileQuery counter is at: $FileQuery" #If Limit for retrys is reached IF (($FileQuery -eq $FileQuery_Limit) -or ($FileQuery -gt $FileQuery_Limit)) { Func-Path-Check -Path $EscalationPath #If file is available IF ((Func-File-check-state -FilePath_and_FileName $Item.FullName -filechecktyp write) -eq 'writeable') { #If File will be renamed by a set prefix IF (($newfilename -gt $NULL) -and ($FileNameConstructor -eq "prefix")) { Try { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] $FileQuery++ Set-Variable -Name DBSQL_NewFilename -Value (Split-Path -Leaf (Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $EscalationPath -move_or_copy move -newfilename_prefix $newfilename)) Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "UPDATE TBDD_LURATECH_ERROR SET FILEQUERY=$FileQuery,COMMENT='Die Verarbeitung der Datei, ist zu oft im Luratech Prozess fehlgeschlagen! Die Datei wurde umbenannt zu - $DBSQL_NewFilename - und in den Ordner - $EscalationPath - verschoben.',CHANGED_WHO='Script: $ScriptName - User: $env:username',CHANGED_WHEN='$Timestamp4' WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash';" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } #end catch } #end if #If File will be renamed ELSEIF (($newfilename -gt $NULL) -and ($FileNameConstructor -eq "complete")) { IF ($newfilename -like "*_") { #If exisits, remove last "_" from new filename Set-Variable -Name newfilenamelength -Value (($newfilename.Length)-1) Set-Variable -Name newfilename -Value ($newfilename.Remove($newfilenamelength,1)) } #end if Try { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] $FileQuery++ Set-Variable -Name DBSQL_NewFilename -Value (Split-Path -Leaf (Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $EscalationPath -move_or_copy move -newfilename $newfilename)) Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "UPDATE TBDD_LURATECH_ERROR SET FILEQUERY=$FileQuery,COMMENT='Die Verarbeitung der Datei, ist zu oft im Luratech Prozess fehlgeschlagen! Die Datei wurde umbenannt zu - $DBSQL_NewFilename - und in den Ordner - $EscalationPath - verschoben.',CHANGED_WHO='Script: $ScriptName - User: $env:username',CHANGED_WHEN='$Timestamp4' WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash';" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } #end catch } #end elseif #If File will be renamed by a set suffix ELSEIF (($newfilename -gt $NULL) -and ($FileNameConstructor -eq "suffix")) { IF ($newfilename -like "*_") { #If exisits, remove last "_" from new filename Set-Variable -Name newfilenamelength -Value (($newfilename.Length)-1) Set-Variable -Name newfilename -Value ($newfilename.Remove($newfilenamelength,1)) } #end if Try { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] $FileQuery++ Set-Variable -Name DBSQL_NewFilename -Value (Split-Path -Leaf (Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $EscalationPath -move_or_copy move -newfilename_suffix $newfilename)) Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "UPDATE TBDD_LURATECH_ERROR SET FILEQUERY=$FileQuery,COMMENT='Die Verarbeitung der Datei, ist zu oft im Luratech Prozess fehlgeschlagen! Die Datei wurde umbenannt zu - $DBSQL_NewFilename - und in den Ordner - $EscalationPath - verschoben.',CHANGED_WHO='Script: $ScriptName - User: $env:username',CHANGED_WHEN='$Timestamp4' WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash';" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } #end catch } #end elseif ELSE { Try { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] $FileQuery++ Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $DestinationPath -move_or_copy move Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "UPDATE TBDD_LURATECH_ERROR SET FILEQUERY=$FileQuery,COMMENT='Die Verarbeitung der Datei, ist zu oft im Luratech Prozess fehlgeschlagen! Die Datei wurde in den Ordner - $EscalationPath - verschoben.',CHANGED_WHO='Script: $ScriptName - User: $env:username',CHANGED_WHEN='$Timestamp4' WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash';" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } #end catch } #end else } #end if ELSE { Func-Write-Logfile "ERROR: File: $Item is not available for this Script." } #end else } #end if #If Limit for retrys is not reached ELSE { Func-Path-Check -Path $DestinationPath IF ((Func-File-check-state -FilePath_and_FileName $Item.FullName -filechecktyp write) -eq 'writeable') { Try { Set-Variable -Name FileQuery -Value $DBSQLDataSet.Tables[0].rows[0][2].ToString() $FileQuery = $FileQuery -as [Int] $FileQuery++ Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $DestinationPath -move_or_copy move Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "UPDATE TBDD_LURATECH_ERROR SET FILEQUERY=$FileQuery,COMMENT='Die Verarbeitung der Datei, ist wiederholt im Luratech Prozess fehlgeschlagen! Die Datei wurde in den Ordner - $DestinationPath - verschoben.',CHANGED_WHO='Script: $ScriptName - User: $env:username',CHANGED_WHEN='$Timestamp4' WHERE FILENAME_AND_FILEPATH = '$($Item.FullName)' AND FILEHASH = '$FileHash';" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } } #end if ELSE { Func-Write-Logfile "ERROR: File: $Item is not available for this Script." } #end else } #end else } #end if #If there are no rows in DB for this file. ELSE { Try { Func-File-copy-or-move -FilePath_and_FileName $Item.FullName -DestinationPath $DestinationPath -move_or_copy move Func-DB-SQL-Query -DBSQLQueryType write -DBSQLErrorAction stop -DBSQLQuery "INSERT INTO TBDD_LURATECH_ERROR (FILENAME_AND_FILEPATH,FILEQUERY,FILEHASH,COMMENT,ADDED_WHO,ADDED_WHEN) VALUES ('$($Item.FullName)',1,'$FileHash','Die Verarbeitung der Datei, ist erstmals im Luratech Prozess fehlgeschlagen! Die Datei wurde in den Ordner - $DestinationPath - verschoben.','Script: $ScriptName - User: $env:username','$Timestamp4');" Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" } #end try Catch { Func-Write-Logfile -LogLine "ERROR: File: $Item could not be moved, or something went wrong by updating the DB." Func-Write-Logfile -LogLine "-------------------------------------------------------------------------------------------" break } #end catch } #end else } #end foreach Func-Write-Logfile -LogLine "===========================================================================================" } #end foreach } #end if ELSE { Func-Write-Logfile -LogLine "There is/are no Rule(s) to process." } #end else #-----------------------------------------------------------------------------------------------------# ########################################### finishing part ############################################ #-----------------------------------------------------------------------------------------------------# # Löschen alter Log-Dateien. 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}) IF ($Items -eq $null) { Func-Write-Logfile -LogLine "Deleting no old LogFiles." } #end if ELSE { Func-Write-Logfile -LogLine "Deleting old LogFiles:" FOREACH ($Item in $Items) { Try { Remove-Item -Path $Item -Force -Verbose Func-Write-Logfile -LogLine "LogFile: $Item was removed." } #end try Catch { Func-Write-Logfile -LogLine "LogFile: $Item 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 Completed: $ScriptName on $env:computername from Account $env:USERDOMAIN\$env:USERNAME." Func-Write-Logfile -LogLine "*******************************************************************************************" # Definierte Variablen wieder löschen, damit sie nicht im Arbeitsspeicher verbleiben. Remove-Variable -Name ScriptName Remove-Variable -Name ScriptPath Remove-Variable -name ConfigFile Remove-Variable -name ConfigValues Remove-Variable -Name Timestamp1 Remove-Variable -Name Timestamp2 Remove-Variable -Name Timestamp3 Remove-Variable -Name Timestamp4 Remove-Variable -Name feh_rule?? Remove-Variable -Name feh_rulelist Remove-Variable -Name feh_rulevalue Remove-Variable -Name feh_rulevalues Remove-Variable -Name Counter Remove-Variable -Name FileQuery_Limit Remove-Variable -Name SourcePath Remove-Variable -Name newfilename Remove-Variable -Name statictext Remove-Variable -Name filetyps Remove-Variable -Name FileHash Remove-Variable -Name DBSQLDataSet Remove-Variable -Name FileName Remove-Variable -Name FileName_noExt Remove-Variable -Name FileQuery Remove-Variable -Name filestream Remove-Variable -Name EscalationPath Remove-Variable -Name FileNameConstructor Remove-Variable -Name newfilenamelength Remove-Variable -Name DestinationPath Remove-Variable -Name LogFileKeepTime Remove-Variable -Name LogPath Remove-Variable -Name LogPathError Remove-Variable -Name LogPathValue Remove-Variable -Name LogPathValues Remove-Variable -Name DBSQLConnectDatabase Remove-Variable -Name DBSQLConnectIntegratedSecurity Remove-Variable -Name DBSQLConnectPassword Remove-Variable -Name DBSQLConnectServer Remove-Variable -Name DBSQLConnectUser Remove-Variable -Name DBSQLQuery Remove-Variable -Name DBSQLCommand Remove-Variable -Name DBSQLAdapter Remove-Variable -Name DBSQL_NewFilename Remove-Variable -Name FileCheckResult Remove-Variable -Name FilePath_and_FileName Remove-Variable -Name VersionSeperator Remove-Variable -Name SourcePathSplit Remove-Variable -Name FileSeperator Remove-Variable -name FileDelayAge Remove-Variable -Name Item Remove-Variable -Name Items $error.clear()