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

1170 lines
96 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@didalog.de
# Version Number: 1.1.1.0
# Version Date: 24.02.2017
# 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 DestinationPath -Value $NULL -Scope script
Set-Variable -Name MinimumNumOfParams -Value 4 -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.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-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
Write-Host "DEBUG Info: $SourcePath"
# Save the fourth array value in the given parameters of this profile.
Set-Variable -Name DestinationPath -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[3] -Scope local
Write-Host "DEBUG Info: $DestinationPath"
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]$CurrentDate = ($MOCF_ProfileValues | Where({$_ -match '%Date'}))
[String]$CurrentDate = ($CurrentDate -replace('%Date%',(Get-Date -Format 'yyyyMMdd')))
Write-Host "DEBUG Info: FileDelayAge: $CurrentDate"
} #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 | 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
#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"
$FileCheckResult = (Func-File-check-state -FilePath_and_FileName $Item -filechecktyp write)
} #end do
UNTIL (($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 {
#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
} #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})
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 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
Remove-Variable -Name argFileTypes
Remove-Variable -Name argSourcePath
Remove-Variable -Name argDestinationPath
Remove-Variable -Name argFileDelayAge
Remove-Variable -Name ScriptName
Remove-Variable -Name ScriptPath
Remove-Variable -Name ConfigFile
Remove-Variable -Name KonfigWerte
Remove-Variable -Name ZeitStempel1
Remove-Variable -Name Fehler
Remove-Variable -Name LogDatei
Remove-Variable -Name LogLine
Remove-Variable -Name LogPathListe
Remove-Variable -Name LogPath
Remove-Variable -Name LogPathEintrag
Remove-Variable -Name LogFileKeepTime
Remove-Variable -Name FileDelayAge
Remove-Variable -Name Item
Remove-Variable -Name ItemMoved
Remove-Variable -Name Items
Remove-Variable -Name ItemsMoved
Remove-Variable -Name Path
Remove-Variable -Name PathTest
Remove-Variable -Name ProzessTest
Remove-Variable -Name VersionSeperator
Remove-Variable -Name Counter
Remove-Variable -Name FileTypes
Remove-Variable -Name FileCheckResult
Remove-Variable -Name FileWhiteList
Remove-Variable -Name FileBlackList
Remove-Variable -Name FileSeperator
Remove-Variable -Name FileCheckCounter
Remove-Variable -Name FileCheckCounterLimit
Remove-Variable -Name MoveOrCopy
Remove-Variable -Name SourcePath
Remove-Variable -Name DestinationPath
Remove-Variable -Name MinimumNumOfParams
Remove-Variable -Name RegExGroup
Remove-Variable -Name RegExGroupIndex
Remove-Variable -Name RegExResult
Remove-Variable -Name Replace
Remove-Variable -Name MOCF_Profile*
$error.clear()