8
0

Anlage des Repos

This commit is contained in:
2024-01-24 16:42:38 +01:00
commit 38d6a271c4
1785 changed files with 3051496 additions and 0 deletions

View File

@@ -0,0 +1,291 @@
Function MoveOrCopy-Item-withLogging {
<#
.SYNOPSIS
Function will copy or move File(s).
.DESCRIPTION
If File already exists in target Path new File will get a Version ~2.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
Datei, Datei1, DateiName, DateiEndung, DateiTest, DateiVersion,ZielPath, MoveorCopy, SourcePath
.REQUIREMENT Variables preSet
VersionSeperator
.REQUIREMENT Functions
Write-Logfile
.VERSION
1.2.1.1 / 17.12.2016
.PARAMETER SourceFile
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 Action
Determine which Action you want to perform <Copy|Move>. Default Value is "Copy".
.PARAMETER NewFileName
Give a String, which get the new Name of the File you are moving.
.PARAMETER NewFileName_prefix
Give a String, which get the new prefix Name of the File you are moving.
.PARAMETER NewFileName_suffix
Give a String, which get the new suffix Name of the File you are moving.
.EXAMPLE
MoveOrCopy-Item-withLogging -SourceFile "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy move
.EXAMPLE
MoveOrCopy-Item-withLogging -SourceFile "E:\Quellpfad\Test.txt" -DestinationPath "E:\Zielpfad" -move_or_copy copy
#>
Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage='Give the full Path and Filename to one File.')]
[ValidateNotNullOrEmpty()]
[String]$SourceFile,
[Parameter(Mandatory=$True,HelpMessage='Give the Target Path you want to move or copy the specified File.')]
[ValidateNotNullOrEmpty()]
[String]$DestinationPath,
[Parameter(Mandatory=$True,HelpMessage='Determine which Action you want to perform <Copy|Move>. Default Value is "Copy".')]
[ValidateSet("copy","move")]
[String]$Action="copy",
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName,
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new prefix Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName_prefix,
[Parameter(Mandatory=$False,HelpMessage='Give a String, which get the new suffix Name of the File you are moving.')]
[ValidateNotNullOrEmpty()]
[String]$NewFileName_suffix
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
$FileTest = Test-Path "$SourceFile" -PathType Leaf
IF ($Filetest -eq 'True') {
Write-Logfile -LogLine ""
$SourcePath = ([System.IO.Path]::GetDirectoryName($SourceFile).ToString())
$FileName = ([System.IO.Path]::GetFileName($SourceFile).ToString())
$FileName_noExt = ([System.IO.Path]::GetFileNameWithoutExtension($SourceFile).ToString())
$FileExtension = ([System.IO.Path]::GetExtension($SourceFile).ToString())
IF (!$VersionSeperator) {
Write-Logfile -LogLine "ERROR: Wrong Function call."
Write-Logfile -LogLine "INFO: Variable VersionSeperator is not valid."
Write-Logfile -LogLine "Application was unplannd terminated."
EXIT
} #end if
IF ($newfilename) {
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) {
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) {
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?
$FileTest = Test-Path "$DestinationPath\$FileName" -PathType Leaf
IF ($Filetest -eq 'True') {
Write-Logfile -LogLine "The File ($Filename) already exists in the target directory, starting Version Check."
[String]$FileNameSplit = ($Filename_noExt -split "$VersionSeperator")
[Int]$FileVersion = $NULL
[Int]$FileVersion = $FileNameSplit[1]
# 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."
$FileName_noExt = $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 "$SourceFile" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Set-Variable -Name FileTemp -Value (Copy-Item -Path "$SourceFile" -Destination "$DestinationPath\$Timestamp3`_$FileName" -PassThru -Force)
Write-Logfile -LogLine "The $Action command has been completed."
Set-Variable -Name FileFinal -Value (Rename-Item -Path "$FileTemp" -NewName "$FileName_noExt$VersionSeperator$FileVersion$FileExtension" -PassThru -Force )
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 ($Action -eq 'move') {
Write-Host "DEBUG Info: Moving action was choosen, will delete source file."
IF ($FileHash_befor -eq $FileHash_after) {
Try {
Remove-Item -Path "$SourceFile" -Force
} #end try
Catch {
Write-Logfile -LogLine "Error removing the source file."
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "HASH Value does mismatch!"
Write-Logfile -LogLine "Aborting delete operation!"
} #end else
} #end if
Return $FileFinal.Fullname
} #end try
Catch {
Write-Logfile -LogLine "Error at $Action command, processing file: $SourceFile"
Write-Logfile -LogLine "Please check your privileges"
exit
} #end catch
} #end if
ELSE {
Set-Variable -Name FileHash_befor -Value (Get-FileHash -Path "$SourceFile" -Algorithm SHA512 | select Hash | Foreach-Object {$_ -replace "@{Hash=", ""} | Foreach-Object {$_ -replace "}", ""})
Set-Variable -Name FileFinal -Value (Copy-Item -Path "$SourceFile" -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 "}", ""})
Write-Logfile -LogLine "The $Action command has been completed for file: $SourceFile"
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 ($Action -eq 'move') {
Write-Host "DEBUG Info: Moving action was choosen, will delete source file."
IF ($FileHash_befor -eq $FileHash_after) {
Try {
Remove-Item -Path "$SourceFile" -Force
} #end try
Catch {
Write-Logfile -LogLine "Error removing the source file."
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "HASH Value does mismatch!"
Write-Logfile -LogLine "Aborting delete operation!"
} #end else
} #end if
ELSEIF ($Action -eq 'copy') {
Write-Host "DEBUG Info: Coping action was choosen, will not delete original file."
} #end elseif
Return $FileFinal.Fullname
} #end else
} #end if
ELSE {
Write-LogFile -LogLine "Cannot find Source File!"
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,122 @@
Function Remove-Item-withLogging {
<#
.SYNOPSIS
Function will delete Items selected by Path, Name and Age.
.DESCRIPTION
Function will delete Items selected by Path, Name and Age, with logging this.
For a successful performed deletion, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Variables
Path, FileKeepTime, FileBaseName, Item, Items
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
Number: 1.1.1.1 / Date: 25.04.2017
.PARAMETER Path
Give the Full Path, where the Item(s) located, which should be deleted.
.PARAMETER FileKeepTime
Give the time in Days, which Items should be deleted, which are older than...
.PARAMETER FileBaseName
Give the <Filename> which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.
.PARAMETER FileExtension
Give the FileExtension which Files will be selected for deletion (Default: log).
.EXAMPLE
Remove-Item-withLogging -Path "E:\LogFiles" -FileKeepTime 5 -FileBaseName Filename
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the Full Path, where the Item(s) located, which should be deleted.')]
[ValidateNotNullOrEmpty()]
[String]$Path=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the time in Days, which Item(s) should be deleted, which are older than...')]
[ValidateRange(0,1000)]
[Int]$FileKeepTime=$NULL,
[Parameter(Mandatory=$True,HelpMessage='Give the Filename which will be selected, the Item(s) to delete. Given <Filename> will be set with Wildcards: *<Filename>*.')]
[ValidateNotNullOrEmpty()]
[String]$FileBaseName=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Give the FileExtension which Files will be selected for deletion (Default: log).')]
[ValidateNotNullOrEmpty()]
[String]$FileExtension="log"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ($FileKeepTime -gt 0) {
Write-Logfile -LogLine "Files should be removed which are older than $FileKeepTime Day(s)."
[Array]$Items = (Get-ChildItem -Path "$Path\*" -Filter *.$FileExtension | where {$_.Name -like "*$FileBaseName*" -and $_.lastwritetime -lt $((Get-Date).AddDays(-$FileKeepTime)) -and -not $_.psiscontainer})
IF ($Items.count -le 0) {
Write-Logfile -LogLine "Found no old Files."
Return $False
} #end if
ELSE {
Write-Logfile -LogLine "Deleting old Files (Found: $($Items.count)) :"
Try {
$Items | Remove-Item -Path $Item -Force -Verbose -ErrorAction Stop
Write-Logfile -LogLine "Files were removed!"
Return $True
} #end try
Catch {
Write-Logfile -LogLine "Cannot remove Files!"
Write-Logfile -LogLine "Please check your privileges!"
Return $False
} #end catch
} #end else
} #end if
ELSE {
Write-Logfile -LogLine "You disabled File deletion, they all will be kept."
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,361 @@
Function Restart-windreamClient-withLogging {
<#
.SYNOPSIS
Restart windream Client Components via COM Interface
.DESCRIPTION
If Connection to the windream Server gets interrupted (network loss, eg.), it is neccessery to restart the Client Components.
Otherwise you can Stop or Start Client Components with this Function.
For a successful performed Action, Function will Return $True, for unccessful $False.
.REQUIREMENT General
PowerShell V3, windream Client Connectivity (>=V3.6)
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
windreamControlCenter, windreamIndexService, ServiceTest, Action
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
1.1.0.1 / 22.11.2016
.PARAMETER Action
Determine which Action you want to perform <Stop|Restart|Start>. Default Value is <Restart>.
.PARAMETER ServiceTest
Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.
.EXAMPLE
Restart-windreamClient
.EXAMPLE
Restart-windreamClient -Action Start
.EXAMPLE
Restart-windreamClient -Action Start -ServiceTest $False
#>
Param (
[Parameter(Mandatory=$False,HelpMessage='Determine which Action you want to perform <Stop|Restart|Start>. Default Value is "Restart".')]
[ValidateSet("Stop","Restart","Start")]
[String]$Action="Restart",
[Parameter(Mandatory=$False,HelpMessage='Set on $True, if Function should check for a running windream vfs Client Service. If it is and Service is stopped, Function will try to start Service. Default Value is $True.')]
[ValidateSet($True,$False)]
[Switch]$ServiceTest=$True
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Host "DEBUG Info: Write-LogFile - Module exists."
#If Servie Test was enabled (by default true) check if windream vfs Service is running
IF ($ServiceTest -eq $True) {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is enabled!"
#Check if windream vfs Service is installed
Try {
[Object]$ServiceTest = $NULL
[Object]$ServiceTest = Get-Service -Name vfssvc -ErrorAction Stop
Write-LogFile -LogLine "Found Service: vfssvc"
Write-LogFile -LogLine "Service is currently: $((Get-Service -Name vfssvc).Status)"
} #end try
Catch {
Write-LogFile -LogLine "WARNING: windream Client seems not to be installed completely."
Write-LogFile -LogLine "Missing Service: vfssvc"
} #end catch
} #end if
#If Servie Test is disabled
ELSE {
Write-LogFile -LogLine " "
Write-LogFile -LogLine "Service Test is disabled!"
} #end else
#Try to create windream Objects
Try {
[Object]$windreamControlCenter = New-Object -ComObject "Wmcc.ControlCenter" -ErrorAction Stop
[Object]$windreamIndexService = New-Object -ComObject "WMIndexServer.WMIdxSvControl" -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Wmcc.ControlCenter or WMIndexServer.WMIdxSvControl!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#If Function was called to Stop windream Client Components
IF ($Action -like "Stop") {
Write-LogFile -LogLine "Stop windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
$windreamControlCenter.ExitCC(0) | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end if
#If Function was called to Restart windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Restart windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Restart") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Restart windream Client Components."
#Try to stop windream Client Components
Try {
Write-Logfile -LogLine "Stopping windream Client Components!"
$windreamControlCenter.StartVFSService(0) | Out-Null
$windreamIndexService.Shutdown() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot stop windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was enabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Object])) {
#Checking if windream vfs Service is running
IF ((Get-Service -Name vfssvc).Status -ne 'running') {
Write-LogFile -LogLine "Warning: windream vfs Service is not running!"
Try {
Write-Logfile -LogLine "Trying to Start/Restart the windream vfs Service!"
Stop-Service -Name vfssvc -ErrorAction SilentlyContinue
Start-Service -Name vfssvc -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot Start/Restart windream vfs Service!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-LogFile -LogLine "windream vfs Service is running!"
} #end else
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called to Start windream Client Components and Service Test was disabled
ELSEIF (($Action -like "Start") -and ($ServiceTest -is [Switch])) {
Write-LogFile -LogLine "Start windream Client Components."
#Try to start windream Client Components
Try {
Write-Logfile -LogLine "Starting windream Client Components!"
$windreamControlCenter.StartVFSService(1) | Out-Null
$windreamIndexService.Start() | Out-Null
} #end try
Catch {
Write-Logfile -LogLine "Cannot start windream Client Components!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Return $True
} #end elseif
#If Function was called invalid Values, which should be not possible be the ValidateSet of the Function Parameters
ELSE {
Write-Logfile -LogLine "Function Call went wrong, please check the ValidateSet"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,211 @@
Function Start-SQLDB-Query-withLogging {
<#
.SYNOPSIS
Function will send a SQL Query to a SQL DB.
.DESCRIPTION
Function will send a SQL Query to a SQL DB. If you set a read command (SELECT ...), function will return a dataset.
.REQUIREMENT General
PowerShell V2 and Function "Write-Logfile".
.REQUIREMENT Variables
DBSQLQuery, DBSQLQueryType, DBSQLConnectServer, DBSQLConnectUser, DBSQLConnectPassword, DBSQLConnectDatabase, DBSQLConnectIntegratedSecurity, DBSQLCommand, DBSQLAdapter, DBSQLConnection
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.0.1.0 / Date: 24.09.2017
.PARAMETER DBSQLQuery
Give a Standard T-SQL Query
.PARAMETER DBSQLQueryType
Give read or write, depends on your planned action ("select" is only read, "insert" and "update" are write)
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType read -DBSQLQuery "SELECT * from TABLE;"
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "INSERT INTO TABLE (column1,column2,column3) VALUES ('Text1', Zahl1, Zahl2) WHERE column4 = 'Text2';"
.EXAMPLE
Func-DB-SQL-Query -DBSQLQueryType write -DBSQLQuery "UPDATE TABLE SET column1='Text1',column2=Zahl1,column3=Zahl2 WHERE column4 = 'Text2';"
#>
Param (
[Parameter(Position=0,Mandatory=$False,HelpMessage='Give the SQL Servername or Server name incl. Instance name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectServer=(Get-Variable -Name DBSQLConnectServer -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=1,Mandatory=$False,HelpMessage='Give the database user name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectUser=(Get-Variable -Name DBSQLConnectUser -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the database user password')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectPassword=(Get-Variable -Name DBSQLConnectPassword -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=3,Mandatory=$False,HelpMessage='Give the database name')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectDatabase=(Get-Variable -Name DBSQLConnectDatabase -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=4,Mandatory=$False,HelpMessage='Determ if current login credentials should be used for database login ()')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLConnectIntegratedSecurity=(Get-Variable -Name DBSQLConnectIntegratedSecurity -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=5,Mandatory=$True,HelpMessage='Specify the SQL Query')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLQuery,
[Parameter(Position=6,Mandatory=$False,HelpMessage='Determ if Query was for read or write operations')]
[ValidateSet("read","write")]
[STRING]$DBSQLQueryType='read',
[Parameter(Position=7,Mandatory=$False,HelpMessage=')')]
[ValidateNotNullOrEmpty()]
[STRING]$DBSQLErrorAction='continue'
) #end param ValueFromPipeline=$True
IF (Get-Module -Name "Write-LogFile") {
Write-Logfile -LogLine ""
Write-Logfile -LogLine "Connecting with DB:"
Write-Logfile -LogLine "Server = $DBSQLConnectServer, uid=$DBSQLConnectUser, pwd=<set in ConfigFile>, Database = $DBSQLConnectDatabase, Integrated Security = $DBSQLConnectIntegratedSecurity"
Try {
$DBSQLConnection = New-Object System.Data.SqlClient.SqlConnection
$DBSQLConnection.ConnectionString = "Server = $DBSQLConnectServer; uid=$DBSQLConnectUser; pwd=$DBSQLConnectPassword; Database = $DBSQLConnectDatabase; Integrated Security = $DBSQLConnectIntegratedSecurity"
Write-Logfile -LogLine "Processing SQL Query:"
Write-Logfile -LogLine $DBSQLQuery
IF ($DBSQLQueryType -eq 'read') {
Try {
$DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand
$DBSQLCommand.CommandText = $DBSQLQuery
$DBSQLCommand.Connection = $DBSQLConnection
$DBSQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$DBSQLAdapter.SelectCommand = $DBSQLCommand
$DBSQLDataSet = New-Object System.Data.DataSet
$DBSQLConnection.Open()
$DBSQLAdapter.Fill($DBSQLDataSet)
$DBSQLConnection.Close()
Write-Logfile -Logline "SQL Query result with $($DBSQLDataSet.Tables[0].Rows.Count) row(s)."
#$DBSQLDataSet.Tables[0].Rows | Out-GridView
Return $DBSQLDataSet
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to process SQL Query (read)!"
IF ($ErrorAction -eq 'continue') {
Write-Logfile -LogLine "Program will continue, anyway."
} #end if
ELSEIF ($ErrorAction -eq 'stop') {
Write-Logfile -LogLine "Program will stop."
exit
} #end elseif
ELSE {
Write-Logfile -LogLine "Invalid Value for Parameter DBSQLErrorAction detected."
Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'."
Write-Logfile -LogLine "Program will continue, anyway."
} #end else
} #end catch
} #end if
ELSEIF ($DBSQLQueryType -eq 'write') {
Try {
$DBSQLCommand = New-Object System.Data.SqlClient.SqlCommand
$DBSQLCommand.CommandText = $DBSQLQuery
$DBSQLCommand.Connection = $DBSQLConnection
$DBSQLConnection.Open()
$DBSQLCommand.ExecuteNonQuery()
$DBSQLConnection.Close()
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to process SQL Query (write)!"
IF ($ErrorAction -eq 'continue') {
Write-Logfile -LogLine "Program will continue, anyway."
} #end if
ELSEIF ($ErrorAction -eq 'stop') {
Write-Logfile -LogLine "Program will stop."
exit
} #end elseif
ELSE {
Write-Logfile -LogLine "Invalid Value for parameter DBSQLErrorAction detected."
Write-Logfile -LogLine "Allowed Values are 'continue' or 'stop'."
Write-Logfile -LogLine "Program will continue, anyway."
} #end else
} #end catch
} #end elseif
ELSE {
Write-Logfile -LogLine "ERROR: Invalid parameter for function!"
} #end else
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to etablish a DB Connection!"
} #end catch
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,351 @@
Function Start-windreamSession-withLogging {
<#
.SYNOPSIS
Start a connection / Session with a windream Server.
.DESCRIPTION
To work in or with windream, you need to start a Session with a windream Server, to access its files, folders and indices.
The windream Drive letter which was retrived by running this module, will be set for the whole Script.
For Impersonation Login Methode, all these Parameters must be set: windreamServer, windreamDomain, windreamUserName and windreamUserPassword.
Function returns with the whole windreamSession Object if connection was successfully established, otherwise with a $False.
.REQUIREMENT General
PowerShell V3, windream Client Connectivity (>=V3.6)
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
windreamServer, windreamVersion, windreamServerBrowser, windreamConnect, windreamSession, windreamDriveLetter, windreamDriveLetterMapping, PathTest
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-LogFile
.VERSION
1.2.0.0 / 02.12.2016
.PARAMETER windreamServer
Optional Parameter. Give Server Name of a specific windream Server, you want to connect with. Otherwise default will be choosen.
.PARAMETER windreamDomain
Optional Parameter. Give a Windows Domain (which is windream autorisiered) for Impersonation Login Methode. Otherwise current domain will be choosen.
.PARAMETER windreamUserName
Optional Parameter. Give a Windows User Name (who is windream autorisiered) for Impersonation Login Methode. Otherwise current User Name will be choosen.
.PARAMETER windreamUserPassword
Optional Parameter. Give the Password for the User name you set bevor in $windreamUserName for Impersonation Login Methode.
.PARAMETER windreamVersion
Optional Parameter. Give the minimum Version of windream, to make sure later function calls will work (Example 3.6, 4.0, ...).
.PARAMETER windream64Bit
Optional Parameter. Available since windream 6.0. Necessary, if following functions need 64Bit Integer Support (eg. GetWMObjectByIdEx64(WMEntity aWMEntity, int64 aWMObjectId)).
.PARAMETER windreamDriveLetterMapping
Optional Parameter. If windream Drive Letter was set in the windream Client config, call this Parameter using $true, to check the Mapping in the Windows Explorer. Default Value is "$True".
.EXAMPLE
Start-windreamSession
.EXAMPLE
Start-windreamSession -windreamVersion "3.6" -windream64Bit <$True|$False>
.EXAMPLE
Start-windreamSession -windreamServer <ServerName> -windreamDomain <domain.local> -windreamUserName <UserName> -windreamUserPassword <UserPassword>
.EXAMPLE
Start-windreamSession -windreamVersion "3.6" -windream64Bit <$True|$False> -windreamServer <ServerName> -windreamDomain <domain.local> -windreamUserName <UserName> -windreamUserPassword <UserPassword>
#>
[cmdletbinding()]
Param (
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give Server Name of a specific windream Server, you want to connect with. Otherwise default will be choosen.')]
[AllowEmptyString()]
[String]$windreamServer=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give a Windows Domain (which is windream autorisiered) for Impersonation Login Methode. Otherwise current domain will be choosen.')]
[ValidateNotNullOrEmpty()]
[String]$windreamDomain=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give a Windows User Name (who is windream autorisiered) for Impersonation Login Methode. Otherwise current User Name will be choosen.')]
[ValidateNotNullOrEmpty()]
[String]$windreamUserName=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give the Password for the User name you set bevor in $windreamUserName for Impersonation Login Methode.')]
[ValidateNotNullOrEmpty()]
[String]$windreamUserPassword=$NULL,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Give the minimum Version of windream, to make sure later function calls will work (Example 3.6, 4.0, ...). Default Value is 4.0.')]
[ValidateNotNullOrEmpty()]
[String]$windreamVersion="4.0",
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. Available since windream 6.0. Necessary, if following functions need 64Bit Integer Support (eg. GetWMObjectByIdEx64(WMEntity aWMEntity, int64 aWMObjectId)). Default Value is $False')]
[ValidateSet($True,$False)]
[Switch]$windream64Bit=$False,
[Parameter(Mandatory=$False,HelpMessage='Optional Parameter. If windream Drive Letter was set in the windream Client config, call this Parameter using $true, to check the Mapping in the Windows Explorer. Default Value is "$True".')]
[ValidateSet($True,$False)]
[Switch]$windreamDriveLetterMapping=$True
) #end param
#Clear Error Variable
$error.clear()
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Host "DEBUG Info: Write-LogFile - Module exists."
#If Function was called without an explicite windream Server, try to get the default
IF (!$windreamServer) {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Function was called without a specific windream Server,"
Write-Logfile -LogLine "trying to find the default windream Server."
Try {
$windreamServerBrowser = New-Object -ComObject "WMOBrws.ServerBrowser" -ErrorAction Stop
$windreamServer = $windreamServerBrowser.GetCurrentServer()
Write-Logfile -LogLine "windream Server is: $windreamServer"
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOBrws.ServerBrowser!"
Write-Logfile -LogLine "And/Or unable the retrieve default windream Server!"
$windreamServer = $NULL
} #end catch
} #end if
#If Function was called with an explicite windream Server
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Function was called with specific windream Server, trying to connect to $windreamServer"
Write-Logfile -LogLine "Remember: Since windream 4.0, this will only work if you are using Impersonation Login Methode."
Write-LogFile -Logline "windreamServer, windreamDomain, windreamUserName and windreamUserPassword"
Try {
$windreamServerBrowser = New-Object -ComObject "WMOBrws.ServerBrowser" -ErrorAction Stop
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOBrws.ServerBrowser!"
Return $False
} #end catch
} #end else
#Go ahead if windreamServer is not null and is reachable via network ping
IF (($windreamServer) -and (Test-Connection -ComputerName $windreamServer -Count 1 -ErrorAction SilentlyContinue)) {
Try {
$windreamConnect = New-Object -ComObject "Windream.WMConnect" -ErrorAction Stop
$windreamConnect.MinReqVersion = $windreamVersion
$windreamConnect.ClientSupports64BitID = $windream64Bit
Write-Logfile -LogLine "windream Connect created!"
} # end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Windream.WMSession!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
Try {
$windreamSession = New-Object -ComObject "Windream.WMSession" #-ErrorAction Stop
Write-Logfile -LogLine "windream Session created!"
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class Windream.WMSession!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
#Use Impersonation Login methode, if these three Parameters are set (-gt $NULL).
IF (($windreamUserName) -and ($windreamUserPassword) -and ($windreamDomain)) {
Try {
$windreamConnect.ModuleId = 9
$windreamImpersonation = New-Object -ComObject "WMOTool.WMUserIdentity" -ErrorAction Stop
$windreamImpersonation.aDomain = $windreamDomain
$windreamImpersonation.aPassword = $windreamUserPassword
$windreamImpersonation.aServerName = $windreamServer
$windreamImpersonation.aUserName = $windreamUserName
Try {
Write-Logfile -LogLine "Try to Login Impersonation"
$windreamSession = $windreamConnect.Login($windreamImpersonation)
} #end try
Catch {
Write-Logfile -LogLine "Cannot Login into windream Session!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end try
Catch {
Write-Logfile -LogLine "Cannot create Object from windream Class WMOTool.WMUserIdentity!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end if
#If Impersonation Login methode was not set, try to login with current username, domain and password
ELSE {
Try {
Write-Logfile -LogLine "Try to Login with current credentials."
$windreamConnect.LoginSession($windreamSession)
} #end try
Catch {
Write-Logfile -LogLine "Cannot Login into windream Session!"
Write-Logfile -LogLine $Error
Return $False
} #end catch
} #end else
IF ($windreamSession.aLoggedin -eq $True) {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Connection established"
Write-Logfile -LogLine "You are connected with $($windreamConnect.ServerName) as $($windreamSession.aUser.aName)"
Write-Host "DEBUG Info: Do not forget to Logout Session after finished work."
$windreamDriveLetter = $windreamServerBrowser.GetServerValue($windreamServer, "DriveLetter", 0)
IF ($windreamDriveLetter) {
Write-Logfile -LogLine "The configured windream Drive Letter is: $windreamDriveLetter"
Set-Variable -Name windreamDriveLetter -Value $windreamDriveLetter -Scope Global -ErrorAction SilentlyContinue
$PathTest = Test-Path -Path "$windreamDriveLetter`:\" -PathType Container
IF ($PathTest -eq $True) {
Write-Logfile -LogLine "The configured windream Drive Letter seems to be connected, as well!"
} #end if
ELSE {
Write-Logfile -LogLine "The configured windream Drive Letter seems not to be connected!"
IF ($windreamDriveLetterMapping -eq $True) {
Try {
Write-Logfile -LogLine "Try to connect the windream Drive ..."
Remove-PSDrive -Name "$windreamDriveLetter" -Force -Scope Global -ErrorAction SilentlyContinue
$PathTest = New-PSDrive -Name "$windreamDriveLetter" -PSProvider FileSystem -Root "\\windream\objects" -Persist -Scope Global -ErrorAction Stop
Write-Logfile -LogLine "windream Drive Letter $PathTest should be connected, now!"
} #end try
Catch {
Write-Logfile -LogLine "Cannot map the windream Drive!"
Set-Variable -Name windreamDriveLetter -Value $NULL -Scope Global -ErrorAction SilentlyContinue
} #end catch
} #end if
ELSE {
Write-Logfile -LogLine "Will not try to map the windream Drive..."
} #end else
} #end else
} #end if
ELSE {
Write-Logfile -LogLine "WARNING: There is no windream Drive Letter configured."
Write-Logfile -LogLine "This could cause access problems!"
Write-Logfile -LogLine "Please check your windream Alias Settings!"
} #end else
Return $windreamSession
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Connection refused"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
#Stop if windream Server was unavailable
ELSE {
Write-Logfile -LogLine "Cannot retrieve windream Server to connect with or test connection failed!"
Write-Logfile -LogLine $Error
Return $False
} #end else
} #end if
ELSE {
Write-Host ""
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,167 @@
Function Test-FileState-withLogging {
<#
.SYNOPSIS
Function will check if given File is accessible.
.DESCRIPTION
This Function will check the accessibility of a File.
If the given File was readable, Function will Return "readable"
Additional Function can be called with the Parameter "-Action writetest",
then after a successful readtest, there will be a writetest.
On Success Return Value will be "writeable".
If File doesn exist Function will return $NULL.
If File Attribute was not editable (by resetting them),
Function will return "noteditable".
.REQUIREMENT General
PowerShell V3
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
SourceFile, SourceFileAttributeReset, Action, FileInfo, FileCheckResult, FileStream
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.1.0.0 / Date: 21.03.2017
.PARAMETER SourceFile
Give the full Path and Filename you want to check.
.PARAMETER SourceFileAttributeReset
Set on $True, if Function should reset the File Attributes (if ReadOnly was set). Default Value is $True.
.PARAMETER Action
Determine which Action you want to perform <readtest|writetest>. Default Value is "readtest".
.EXAMPLE
Test-FileState-withLogging -SourceFile "E:\Path\file_to_check.txt"
.EXAMPLE
Test-FileState-withLogging -SourceFile "E:\Path\file_to_check.txt" -Action writetest
#>
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the full Path and Filename you want to check.')]
[ValidateNotNullOrEmpty()]
[String]$SourceFile,
[Parameter(Mandatory=$False,HelpMessage='Set on $True, if Function should reset the File Attributes (if ReadOnly was set). Default Value is $True.')]
[ValidateSet($True,$False)]
[Switch]$SourceFileAttributeReset=$True,
[Parameter(Mandatory=$False,HelpMessage='Determine which Action you want to perform <readtest|writetest>. Default Value is "readtest".')]
[ValidateSet("readtest","writetest")]
[String]$Action="readtest"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
IF ((Test-Path -Path $SourceFile) -eq 'True') {
$FileInfo = (New-Object System.IO.FileInfo $SourceFile)
$FileCheckResult = "unknown"
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Checking if file: $SourceFile is locked/readonly..."
IF (($FileInfo.Attributes -match "ReadOnly") -and ($SourceFileAttributeReset -eq $True)) {
Write-Host "DEBUG Info: ReadOnly Attribute found, removing if possible"
Try {
$FileInfo.Attributes="Archive","Temporary"
Write-Host "DEBUG Info: File Attributes has been recessed!"
} #end try
Catch {
Write-Logfile -LogLine "WARNING: Cannot recessed File Attributes!"
Return "noteditable"
} #end catch
} #end if
Write-Logfile -LogLine "Checking if file: $SourceFile is readable."
# Check if file is readable
Try {
$FileStream = $FileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::Read)
Write-Host "DEBUG Info: Is file readable?" $FileStream.CanRead
$FileStream.Close()
$FileCheckResult = "readable"
} #end try
Catch {
Write-Logfile -LogLine "File: $SourceFile is not even readable."
Write-Host "DEBUG Info: Is file readable?" $FileStream.CanRead
$FileCheckResult = "notreadable"
} #end catch
# Check if file is writeable
IF (($FileCheckResult -eq "readable") -and ($Action -eq 'writetest')) {
Write-Logfile -LogLine "Checking if file: $SourceFile is writeable."
Try {
$FileStream = $FileInfo.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::Write, [System.IO.FileShare]::Write)
Write-Host "DEBUG Info: Is file writeable?" $FileStream.CanWrite
$FileStream.Close()
$FileCheckResult = "writeable"
} #end try
Catch {
Write-Logfile -LogLine "File: $SourceFile is not writeable."
Write-Host "DEBUG Info: Is file writeable?" $FileStream.CanWrite
$FileCheckResult = "notwriteable"
} #end catch
} #end if
Write-Logfile -LogLine "File $SourceFile checked with result: $FileCheckResult"
Return $FileCheckResult
} #end if
ELSE {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Given file: $SourceFile seems not to exist, or access is denied."
Return $NULL
} #end else
} #end if
ELSE {
Write-Host " "
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,114 @@
Function Test-Path-withLogging {
<#
.SYNOPSIS
Function will check the given Path for existence.
.DESCRIPTION
If Path doesn´t exist, Function will try to create it.
You can disable the create Function by calling with "-Action "ignore"".
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
Path, PathTest
.REQUIREMENT Variables preSet
<NONE>
.REQUIREMENT Functions
Write-Logfile
.VERSION
Number: 1.0.1.0 / Date: 17.12.2016
.PARAMETER Path
Give the full Path you want to check or create.
.PARAMETER Action
Determine which Action you want to perform <create|ignore". Default Value is "create".
.EXAMPLE
Test-Path-withLogging -Path "E:\Path\to\create"
.EXAMPLE
Test-Path-withLogging -Path "E:\Path\to\check" -Action "ignore"
#>
Param (
[Parameter(Mandatory=$True,HelpMessage='Give the full Path you want to check.')]
[ValidateNotNullOrEmpty()]
[String]$Path,
[Parameter(Mandatory=$False,HelpMessage='Determine which Action you want to perform <create|ignore". Default Value is "create".')]
[ValidateSet("create","ignore")]
[String]$Action="create"
) #end param
#Checking if "Write-LogFile" Module was loaded
IF (Get-Module -Name "Write-LogFile") {
Write-Logfile -LogLine " "
Write-Logfile -LogLine "Checking Path $Path for existence."
$PathTest = Test-Path -PathType Container $Path
#If given Path already exists
IF ($PathTest -eq "True") {
Write-Logfile -LogLine "Path $Path already exists and can be used."
Return $True
} #end if
#If given Path does not exist
ELSE {
Write-Logfile -LogLine "Path $Path does not exist."
IF ($Action -eq "create") {
Try {
Write-Logfile -LogLine "Path $Path has to been created."
New-Item -Path $Path -ItemType directory -Force -ErrorAction Stop
Return $True
} #end try
Catch {
Write-Logfile -LogLine "ERROR: Unable to create Path."
Write-Logfile -LogLine "INFO: Maybe there is an access or rights Problem."
Return $False
} #end catch
} #end if
ELSE {
Return $False
} #end else
} #end else
} #end if
ELSE {
Write-Host " "
Write-Host "DEBUG Info: Write-LogFile - Module does not exist!"
Write-Host "DEBUG Info: Please load the Module and try again, running this Function/Module!"
Write-Host "DEBUG Info: Exiting, because of this Issue."
EXIT
} #end else
} #end function

View File

@@ -0,0 +1,232 @@
Function Write-LogFile {
<#
.SYNOPSIS
Function will write a given String to a Logfile.
.DESCRIPTION
Just like the cmdlet Write-Host, this Function will display Output on the Console.
Parallel Output will be written into a designated LogFile.
It is recommended to init the LogPath Variable with $Null and the LogPaths Variable with a possible Path,
which has to be checked for accessible.
This is important, because if given Path was inaccessible (-> Access Test failed), Function will try some other Paths for accessible.
These are: The ScriptPath (\Logs) from, which triggerd this Function and $env:temp\Digital Data\$ScriptName\Logs.
After a successful Access Test, Function will set the Variable LogPath, with the first accessible Path tested.
Function will not give any Return Values, because if it is impossible to write a LogFile, Function will force the whole Script to exit.
.REQUIREMENT General
PowerShell V2
.REQUIREMENT Assembly
<NONE>
.REQUIREMENT Variables
PathTest, FileTest, LogPaths, Counter1, LogLine
.REQUIREMENT Variables preSet
LogFile, LogPath, ScriptName, ScriptPath
.REQUIREMENT Functions
<NONE>
.VERSION
Number: 2.1.0.1 / Date: 23.09.2017
.PARAMETER LogLine
Give the String you want to be written into the Logfile.
.EXAMPLE
Write-LogFile -LogLine "Write this in my Log, please."
.EXAMPLE
Write-LogFile -LogLine "Write this Variabel $Variable in my Log, please."
#>
Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage='Give the String you want to be written into the Logfile.')]
[AllowEmptyString()]
[STRING]$LogLine,
[Parameter(Position=1,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$LogFile=(Get-Variable -Name LogFile -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=2,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$LogPath=(Get-Variable -Name LogPath -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=3,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$ScriptName=(Get-Variable -Name ScriptName -Scope Global -ValueOnly -ErrorAction SilentlyContinue),
[Parameter(Position=4,Mandatory=$False,HelpMessage='Give the String you want to be written into the Logfile.')]
[ValidateNotNullOrEmpty()]
[STRING]$ScriptPath=(Get-Variable -Name ScriptPath -Scope Global -ValueOnly -ErrorAction SilentlyContinue)
) #end param
#Clear Error Variable
$error.clear()
IF (!$LogFile) {
$LogFile = ((($MyInvocation.MyCommand.Name) -split "\.")[0].ToString())+".log"
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for LogFile, was set to: $LogFile"
} #end if
IF (!$LogPath) {
$LogPath = $PSScriptRoot+"\Logs"
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for LogPath, was set to: $LogPath"
} #end if
IF (!$ScriptName) {
$ScriptName = ((($MyInvocation.MyCommand.Name) -split "\.")[0].ToString())
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for ScriptName, was set to: $ScriptName"
} #end if
IF (!$ScriptPath) {
$ScriptPath = $PSScriptRoot
Write-Host "DEBUG Info - Write-LogFile: FailSafe Setting for ScriptPath, was set to: $ScriptPath"
} #end if
# This if / else block is only for determine the LogPath
IF ((!$LogPath) -or ($LogPath -eq $PSScriptRoot+"\Logs")) {
Write-Host ""
Write-Host "DEBUG Info - Write-LogFile: LogPath is currently not set!"
[Array]$LogPaths = $LogPaths
[Array]$LogPaths = ($LogPaths += "$ScriptPath\Logs","$env:temp\Digital Data\$ScriptName\Logs")
[int]$Counter1 = 0
DO {
#Determine the current Array object
[String]$LogPath = [Array]$($LogPaths[$Counter1])
Write-Host ""
Write-Host "DEBUG Info - Write-LogFile: Testing LogPath: $LogPath"
$PathTest = Test-Path -PathType Container "$LogPath"
#Check if Path already exists
IF ($PathTest -eq $True) {
Write-Host "DEBUG Info - Write-LogFile: LogPath seems already to exists: $LogPath"
} #end if
ELSE {
#If Path doesnt exist, try to create it!
Try {
Write-Host "DEBUG Info - Write-LogFile: Trying to create LogPath: $LogPath"
New-Item -ItemType Directory -Path "$LogPath" -Force -ErrorAction Stop | Out-Null
Write-Host "DEBUG Info - Write-LogFile: Trying seems to be successful!"
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot create LogPath or access denied!"
Write-Host $Error
} #end catch
} #end else
#Check again if path exists
$PathTest = Test-Path -PathType Container "$LogPath"
IF ($PathTest -eq $True) {
Try {
Write-Host "DEBUG Info - Write-LogFile: Trying to write a TestFile into the LogPath."
New-Item -ItemType File -Path "$LogPath\AccessTest.txt" -Force -ErrorAction Stop | Out-Null
Add-content "$LogPath\AccessTest.txt" -Value "This is a Test!" -Force -ErrorAction Stop | Out-Null
$FileTest = Test-Path -Path "$LogPath\AccessTest.txt" -PathType Leaf -ErrorAction Stop
Remove-Item -Path "$LogPath\AccessTest.txt" -Force -ErrorAction Stop | Out-Null
Write-Host "DEBUG Info - Write-LogFile: Write Test seems to be successful."
Set-Variable -Name LogPath -Value $LogPath -Scope Global -Force
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot write into LogPath or access denied!"
Write-Host $Error
} #end catch
} #end if
ELSE {
Write-Host "DEBUG Info - Write-LogFile: Cannot create LogPath or access denied!"
Write-Host $Error
} #end else
[int]$Counter1++ | Out-Null
} #end do
UNTIL ((($PathTest -eq $True) -and ($FileTest -eq $True)) -or ($Counter1 -eq $($LogPaths.count)) )
} #end if
ELSEIF ($LogPath) {
#Write-Host "DEBUG Info - Write-LogFile: LogPath was already been set!"
#Write-Host "DEBUG Info - Write-LogFile: LogPath is $LogPath"
} #end elseif
ELSE {
Write-Host "Unexpected Error!"
Write-Host $Error
Return $False
} #end else
IF ($LogPath) {
#After LogPath determination - try to log the string
Try {
Write-Host "$LogLine"
Add-content $LogPath\$LogFile -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): $LogLine" -ErrorAction Stop
#Return $True
} #end try
Catch {
Write-Host "DEBUG Info - Write-LogFile: Cannot write to LogFile!"
Write-Host "DEBUG Info - Write-LogFile: Exiting, because of this Issue."
Write-Host $Error
EXIT
} #end catch
} #end if
ELSE {
Write-Host "DEBUG Info - Write-LogFile: Cannot write to LogFile!"
Write-Host "DEBUG Info - Write-LogFile: Exiting, because of this Issue."
Write-Host $Error
EXIT
} #end else
} #end function