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

992 lines
82 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.0.1.2
# Version Date: 07.02.2016
# 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 "Pfadüberprüfung: Prüfe ob LogPath bereits angelegt ist: $LogPathEintrag"
IF ($PfadTest -eq "True")
{
Write-Host "Pfadüberprüfung: LogPath $LogPathEintrag ist bereits angelegt!"
Set-Variable -Name LogPath -Value $LogPathEintrag
break
}
ELSE
{
Write-Host "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 "Pfadüberprüfung: Prüfe ob Pfad erfolgreich angelegt werden konnte."
IF ($PfadTest -eq "True")
{
Write-Host "Pfadüberprüfung: Pfad $LogPathEintrag wurde erfolgreich angelegt."
Set-Variable -Name LogPath -Value $LogPathEintrag
break
}
ELSE
{
Write-Host "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 "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 "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 Func-Dateien-Versionieren {
<#
.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, QuellPath
.VERSION
1.0 / 10.11.2014
.EXAMPLE
Func-Dateien-Versionieren -Datei "E:\Quellpfad\Test.txt" -ZielPath "E:\Zielpfad" -MoveorCopy move
.EXAMPLE
Func-Dateien-Versionieren -Datei "E:\Quellpfad\Test.txt" -ZielPath "E:\Zielpfad" -MoveorCopy copy
.PARAMETER $Datei
Give the full Path to an File.
.PARAMETER $ZielPath
Give the Target path you want to move or copy the specified File.
.PARAMETER $MoveOrCopy
Give this Parameter to determ a copy or a move Order.
#>
Param
(
[String]$Datei,
[String]$ZielPath,
[String]$MoveorCopy
)
IF (($MoveorCopy -ne 'move') -and ($MoveorCopy -ne 'copy'))
{
Func-Write-Logfile -LogLine "ERROR: Wrong Function call."
Func-Write-Logfile -LogLine "INFO: Parameter MoveorCopy accepts only 'move' or 'copy'."
Func-Write-Logfile -LogLine "Application will use the copy Order by default."
Set-Variable -Name MoveOrCopy -Value copy -Scope local
}
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
}
$QuellPath = (split-path "$Datei")
$Datei = (split-path "$Datei" -Leaf)
$DateiTest = Test-Path -PathType Leaf "$ZielPath\$Datei"
IF ($DateiTest -eq 'True')
{
Func-Write-Logfile -LogLine ""
Func-Write-Logfile -LogLine "The File already exists in the Target Directory, starting Version Check."
$Datei1 = ($Datei -split "$VersionSeperator")
$DateiVersion = $Datei1[1]
IF ($DateiVersion -eq $NULL)
{
Func-Write-Logfile -LogLine "Sourcefile imcludes no VersionSeperator."
$Datei1 = ($Datei -split "\.")
$DateiName = $Datei1[0]
$DateiEndung = $Datei1[1]
# Um Version ~1 zu überspringen.
$DateiVersion++
}
ELSE
{
Func-Write-Logfile -LogLine "Sourcefile imcludes VersionSeperator."
$Datei1 = ($Datei1 -split "\.")
$DateiName = $Datei1[0]
$DateiVersion = $Datei1[1]
$DateiEndung = $Datei1[2]
$DateiVersion = $DateiVersion -as [Int]
}
DO
{
Write-Host $DateiVersion; $DateiVersion++
}
while
(
($DateiTest = Test-Path -Path "$ZielPath\$Dateiname$VersionSeperator$DateiVersion.$DateiEndung") -eq 'True'
)
IF ($MoveorCopy -eq 'move')
{
Rename-Item -Path "$QuellPath\$Datei" -NewName "$DateiName$VersionSeperator$DateiVersion.$DateiEndung"
Move-Item -Path "$QuellPath\$Dateiname$VersionSeperator$DateiVersion.$DateiEndung" -Destination "$ZielPath" -Force
Func-Write-Logfile -LogLine "File: $Dateiname$VersionSeperator$DateiVersion.$DateiEndung was moved."
}
ELSEIF ($MoveorCopy -eq 'copy')
{
Copy-Item -Path "$QuellPath\$Datei" -Destination "$QuellPath\$Zeitstempel1´_$Datei" -Force
Rename-Item -Path "$QuellPath\$Zeitstempel1´_$Datei" -NewName "$DateiName$VersionSeperator$DateiVersion.$DateiEndung"
Move-Item -Path "$QuellPath\$Dateiname$VersionSeperator$DateiVersion.$DateiEndung" -Destination "$ZielPath" -Force
Func-Write-Logfile -LogLine "File: $Dateiname$VersionSeperator$DateiVersion.$DateiEndung was copied."
}
Func-Write-Logfile -LogLine "from: $QuellPath to: $ZielPath"
Return "$ZielPath\$Dateiname$VersionSeperator$DateiVersion.$DateiEndung"
}
ELSE {
IF ($MoveorCopy -eq 'move') {
Move-Item -Path "$QuellPath\$Datei" -Destination "$ZielPath" -Force
Func-Write-Logfile -LogLine "File: $Datei was moved,"
} #end if
ELSEIF ($MoveorCopy -eq 'copy') {
Copy-Item -Path "$QuellPath\$Datei" -Destination "$ZielPath" -Force
Func-Write-Logfile -LogLine "File: $Datei was copied."
} #end elseif
Return "$ZielPath\$Datei"
} #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","$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
# 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
# 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
# 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
#If more than four parameters are given, check optional parameters.
IF ($(Get-Variable -Name ("MOCF_Profile"+$Counter) -ValueOnly).count -gt 4) {
# Save the fifth array value in the given parameters of this profile.
Set-Variable -Name FileDelayAge -Value $(get-variable -name ("MOCF_Profile"+$Counter) -ValueOnly)[4] -Scope local
} #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 "-------------------------------------------------------------------------------------------"
#Loop for Item to check if its read- and writeable.
DO {
$FileCheckCounter = $FileCheckCounter -as [int]
$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... that are you waitung for? Do your work! Damn...
ELSE {
Func-Path-Check -Path $DestinationPath
Set-Variable -Name ItemMoved -Value (Func-Dateien-Versionieren -Datei "$Item" -ZielPath $DestinationPath -MoveorCopy $MoveOrCopy) -Scope Script
#Adding Values in ervy foreach run - into dynamic array for later processing
$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 MOCF_Profile*
$error.clear()