Last active
June 8, 2022 14:33
-
-
Save pashalvov/0ca2fe3ff74295ca6076f9e9245a8b26 to your computer and use it in GitHub Desktop.
Скрипт для сжатия старых журналов регистрации 1С
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
# | |
# Скрипт для архивации журнала регистрации 1С Предприятия 8.3 - https://gitlab.pravo.tech/p.lvov/compress-1coldjournals | |
# | |
### | |
$isDebug = $false | |
$ScriptVersion = [version]1.3 | |
$StartScriptDate = Get-Date | |
$LogFileName = (Join-Path $PSScriptRoot ("\logs\" + (Get-Date).ToString("yyyy-MM-dd_HH-mm-ss") + '_1C_Journal_Compress.log')) | |
### Создать папки | |
New-Item (Join-Path $PSScriptRoot 'logs') -ItemType Directory -ErrorAction SilentlyContinue | Out-Null | |
$TempDirPath = (Join-Path $PSScriptRoot 'temp') | |
New-Item $TempDirPath -ItemType Directory -ErrorAction SilentlyContinue | Out-Null | |
### Отчистить TEMP | |
Get-ChildItem $TempDirPath -Force | Remove-Item -Force -ErrorAction SilentlyContinue | |
function Log | |
{ | |
[CmdletBinding()] | |
[Alias()] | |
#[OutputType([String])] | |
Param | |
( | |
# Уровень лога | |
[Parameter(Mandatory = $false, | |
Position = 1)] | |
[ValidateSet("ERR", "INF", "WARN", "DEBUG")] | |
$LogLevel, | |
[Parameter(Mandatory = $true, | |
Position = 0)] | |
[ValidateNotNull()] | |
[ValidateNotNullOrEmpty()] | |
$InputObject | |
) | |
Begin | |
{ | |
if ($LogLevel -like '') { $LogLevel = 'INF' } | |
} | |
Process | |
{ | |
$LogString = (Get-Date -Format 'dd.MM.yyyy HH:mm:ss') + " | " + $LogLevel + " | " + $InputObject | |
$LogString | Out-File -FilePath $LogFileName -Encoding default -Append | |
} | |
End | |
{ | |
} | |
} | |
function Get-1CBaseNamesAndId | |
{ | |
$BaseDir = 'C:\Program Files\1cv8\srvinfo\reg_1541' | |
$BaseListFullName = Join-Path $BaseDir '1CV8Clst.lst' | |
$Results = @() | |
$1CBasesId = Get-Content -Path $BaseListFullName | Select-String -SimpleMatch 'inhouse-saas' | ` | |
ForEach-Object { ($_.Line.Split('{')[1].Split(',')[0]) + ';' + ($_.Line.Split(',')[2]).Replace("`"", '') + ';' + ($_.Line.Split(',')[1]).Replace("`"", '') } | |
$Headers = @('Id', 'Имя', 'Имя БД') | |
foreach ($RawData in ($1CBasesId | ConvertFrom-Csv -Delimiter ';' -Header $Headers | Where-Object { ($_.'Имя' -ne '') -and ($_.'Имя' -notlike '*тест*') })) | |
{ | |
$HashTable = [ordered]@{ | |
'Id' = $RawData.Id | |
'Имя' = $RawData.'Имя' | |
'Имя БД' = $RawData.'Имя БД' | |
'Путь к журналу' = Join-Path $BaseDir ($RawData.Id + '\1Cv8Log') | |
} | |
$Results += New-Object -TypeName PSObject -Property $HashTable | |
} | |
### Debug List - тут можно задать какие БД надо брать | |
$AllowBaseList = @('1C_Zup_OOO', '1C_Buh_OOO', '1C_Zup_AO') | |
### | |
return $Results | Where-Object { $_.'Имя БД' -in $AllowBaseList } | |
} | |
function Get-1COldFiles ($Path) | |
{ | |
$Results = @() | |
$Results += Get-ChildItem -Path ($Path + '\*') -Include *.lgp, *.lgx -Exclude ((Get-Date).ToString('yyyyMMdd') + '*') | |
return $Results | |
} | |
function Test-FileLock | |
{ | |
param ( | |
[parameter(Mandatory = $true)][string]$Path | |
) | |
$oFile = New-Object System.IO.FileInfo $Path | |
try | |
{ | |
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) | |
if ($oStream) | |
{ | |
$oStream.Close() | |
} | |
return $false | |
} | |
catch | |
{ | |
# file is locked by a process. | |
return $true | |
} | |
} | |
Log ("Запуск скрипта. Версия " + $ScriptVersion) | |
$SkipPaths = @() | |
$FinalFilesList = @() | |
$TempFilesList = @() | |
$7ZipFullName = 'C:\Program Files\7-Zip\7z.exe' | |
foreach ($Raw1CData in Get-1CBaseNamesAndId) | |
{ | |
$1CLogsPath = $Raw1CData.'Путь к журналу' | |
$1CBaseName = $Raw1CData.Имя | |
$1CDataBaseName = $Raw1CData.'Имя БД' | |
$FilesList = Get-1COldFiles -Path $1CLogsPath | |
Log ('Файлов найдено для архивации: ' + $FilesList.Count + ' для БД: ' + $1CBaseName) | |
foreach ($RawFileData in $FilesList) | |
{ | |
if (Test-FileLock -Path $RawFileData.FullName) | |
{ | |
Log -LogLevel ERR ('Файл заблокирован и будет пропущена вся БД ' + $Raw1CData.Имя + ': ' + $RawFileData.FullName) | |
$SkipPaths += $RawFileData.DirectoryName | |
} | |
} | |
$FilesList = $FilesList | Where-Object { $_.Directory -notin $SkipPaths } | |
$FinalFilesList += if ($FilesList.Count -gt 0) { $FilesList; $TempFilesList += Join-Path $TempDirPath $1CDataBaseName } | |
if ($FilesList.Count -gt 0) { $FilesList.FullName | Out-File -FilePath (Join-Path $TempDirPath $1CDataBaseName) -Force -Encoding utf8 } | |
} | |
$FinalFilesListCount = $FinalFilesList.Count | |
Log ('Всего файлов: ' + $FinalFilesListCount + '. Файлов будет заархивировано: ' + $FinalFilesList.Count) | |
foreach ($TempFile in $TempFilesList) | |
{ | |
$FileForDelete = Get-Content -Path $TempFile -Encoding UTF8 | |
$ArchiveName = '"' + (Join-Path ([System.IO.FileInfo]$FileForDelete[0]).DirectoryName ((Get-Date).ToString("yyyyMMdd") + '.7z')) + '"' | |
try | |
{ | |
$7ZipExitCode = (Start-Process $7ZipFullName -ArgumentList "a -mx3 $ArchiveName `"@$TempFile`"" -Wait -WindowStyle Hidden -PassThru).ExitCode | |
if ($7ZipExitCode -eq 0) | |
{ | |
Log "Архив успешно создан: $ArchiveName" | |
try | |
{ | |
if ($isDebug) | |
{ | |
Log -LogLevel WARN 'Скрипт в режиме DEBUG и файлы не удаляются' | |
Write-Host 'Скрипт в режиме DEBUG и файлы не удаляются' -ForegroundColor Red | |
Log ("Удаленно " + $FileForDelete.Count + ' после успешной архивации') | |
} | |
else | |
{ | |
$FileForDelete | Remove-Item -Force -ErrorAction Stop | |
Log ("Удаленно " + $FileForDelete.Count + ' после успешной архивации') | |
} | |
} | |
catch | |
{ | |
Log -LogLevel ERR ('Ошибка при удалении файла: ' + $Error[0].Exception.Message) | |
} | |
} | |
else | |
{ | |
Log "Ошибка архивации, код выхода: " + $7ZipExitCode | |
switch ($7ZipExitCode) | |
{ | |
0 {} | |
1 { Log -LogLevel ERR 'Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed.' } | |
2 { Log -LogLevel ERR 'Fatal error' } | |
7 { Log -LogLevel ERR 'Command line error' } | |
8 { Log -LogLevel ERR 'Not enough memory for operation' } | |
255 { Log -LogLevel ERR 'User stopped the process' } | |
Default { Log -LogLevel ERR 'Неизвестный код ошибки 7Zip' } | |
} | |
} | |
} | |
catch | |
{ | |
Log -LogLevel ERR ("ИСКЛЮЧЕНИЕ: Архивация прошла с ошибками: Строка " + $Error[0].InvocationInfo.ScriptLineNumber + ', ' + $Error[0]) | |
} | |
} | |
[timespan]$ScriptRunningTime = (Get-Date) - $StartScriptDate | |
Log ('Скрипт отработал за: ' + $ScriptRunningTime.TotalSeconds + ' сек.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment