new file: functions/StartStoper.ps1 new file: functions/Write-LogMessage.ps1
61 lines
2.2 KiB
PowerShell
61 lines
2.2 KiB
PowerShell
# <>
|
|
#
|
|
# 1) Compress-File -Path C:\Users\userprofile\file.txt -Compression high -DeleteOriginal
|
|
# 2) Compress-File -Path C:\Users\userprofile\file.txt -Compression medium
|
|
#
|
|
# 1 Will compress at High level and after succesfull compression will delete source file.
|
|
# 2 Will just compress file at medium level.
|
|
#
|
|
function Compress-File {
|
|
param (
|
|
[Parameter(Mandatory=$true)]
|
|
[string]$Path,
|
|
[Parameter(Mandatory=$false)]
|
|
[ValidateSet('low', 'medium', 'high')]
|
|
[string]$Compression = 'medium',
|
|
[Parameter(Mandatory=$false)]
|
|
[switch]$DeleteOriginal
|
|
)
|
|
|
|
try {
|
|
# Check if the file exists
|
|
if (!(Test-Path -Path $Path -PathType Leaf)) {
|
|
Write-Error "File $Path does not exist or is not a file."
|
|
return
|
|
}
|
|
|
|
# Set the compression level
|
|
switch ($Compression) {
|
|
'low' { $compressionLevel = [System.IO.Compression.CompressionLevel]::NoCompression }
|
|
'medium' { $compressionLevel = [System.IO.Compression.CompressionLevel]::Fastest }
|
|
'high' { $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal }
|
|
}
|
|
|
|
# Get the file name
|
|
$fileName = [System.IO.Path]::GetFileName($Path)
|
|
$zipFileName = "$($fileName).zip"
|
|
|
|
# Create the path to the ZIP file
|
|
$zipFilePath = Join-Path -Path (Split-Path -Parent -Path $Path) -ChildPath $zipFileName
|
|
|
|
# Compress the file to ZIP format
|
|
$zipArchive = [System.IO.Compression.ZipFile]::Open($zipFilePath, [System.IO.Compression.ZipArchiveMode]::Create)
|
|
$zipEntry = $zipArchive.CreateEntry($fileName)
|
|
$stream = $zipEntry.Open()
|
|
$fileStream = [System.IO.File]::OpenRead($Path)
|
|
$fileStream.CopyTo($stream)
|
|
$fileStream.Dispose()
|
|
$stream.Dispose()
|
|
$zipArchive.Dispose()
|
|
|
|
Write-Output "File $fileName has been compressed to $zipFilePath with compression level '$Compression'."
|
|
|
|
if ($DeleteOriginal) {
|
|
Remove-Item -Path $Path -Force
|
|
Write-Output "Original file $Path has been deleted."
|
|
}
|
|
}
|
|
catch {
|
|
Write-Error "An error occurred while compressing the file: $($_.Exception.Message)"
|
|
}
|
|
} |