8
0
2024-01-24 16:42:38 +01:00

1390 lines
120 KiB
PowerShell
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 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.3.2.0
# Version Date: 08.07.2021
# 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 <ThisScript.ps1>
#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 -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 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 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..."
$Items = Get-ChildItem -Path "$SearchPath" -include $SearchWhiteList -exclude $SearchBlackList -Recurse:$true
} #end if
Else {
Func-Write-Logfile -LogLine "Searching NOT reclusive..."
$Items = Get-ChildItem -Path "$SearchPath" -include $SearchWhiteList -exclude $SearchBlackList -Recurse:$false
} #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
# 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) {
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 ###############################################
#-----------------------------------------------------------------------------------------------------#
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 there are some defined Profiles, starte the main part of this Script.
IF (($($MOCF_ProfileList.count) -gt 0)) {
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
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
Set-Variable -Name Items -Value (Func-File-Collector -SearchPath "$Sourcepath\*" -SearchWhiteList $FileTypes -ReclusiveSwitch $ReclusiveSwitch | where-object {$_.lastwritetime -lt (get-date).addminutes(-$FileDelayAge)} )
} #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()