Найти первый доступный файл для вывода журнала - PullRequest
0 голосов
/ 03 мая 2018

Я работаю над полным переписыванием своей функции ведения журнала, которую я использую для пары сотен сценариев, и пытаюсь сделать ее максимально надежной. Я пытаюсь сделать так, чтобы он был в состоянии создать, пройти через очень простой набор проверок, чтобы найти первый доступный журнал, в который он может записать.

Я пытаюсь записать его, чтобы он пытался записать в каждый файл журнала (в случае, если файлы имеют разрешения, отличные от каталогов)

Логический путь

  • Пройдите по каждому каталогу в списке
  • Посмотрите, есть ли какие-нибудь журналы, которые я могу добавить к
  • Если к ним добавляется
  • Если нет, попробуйте создать новый журнал с добавлением #.
  • Если не удается создать новый журнал, перейдите к следующему каталогу

Этот сценарий не очень сложный, я написал гораздо более сложные сценарии, но по какой-то причине мой мозг не будет обдумывать это, и я продолжаю придумывать неокрепшие, очень повторяющиеся функции, и я пытаюсь сохранить эффективность и скорость как наиболее важный приоритет.

Function TestLogger {
    $WriteTee = @{}
    $WriteTee.LogName  = 'WriteTee.log'
    #$WriteTee.LogName  = "$(((Split-Path -Leaf $script:MyInvocation.MyCommand.Definition)).BaseName).txt"
    $WriteTee.LogPaths = "C:\Windows\",
                         'C:\Users\1151577373E\Documents\Powershell Scripts\AutoUpdater\',
                         "$Env:UserProfile"
                         #"$(Split-Path -Parent $script:MyInvocation.MyCommand.Definition)"

    foreach ($Path in $WriteTee.LogPaths) {
        $Path = [System.IO.DirectoryInfo]$Path
        #Ensure the directory exists and if not, create it.
        if (![System.IO.Directory]::Exists($Path)) {
            try {
                New-Item -Path $Path.Parent.FullName -Name $Path.BaseName -ItemType 'Directory' -ErrorAction Stop -Force | Out-Null
            } catch {
                continue
            }
        }

        #Check to see if there are any existing logs
        $WriteTee.ExistingLogs = Get-ChildItem -LiteralPath $Path -Filter "$(([System.IO.FileInfo]$WriteTee.LogName).BaseName)*$(([System.IO.FileInfo]$WriteTee.LogName).Extension)" |Sort-Object
        if ($WriteTee.ExistingLogs.Count -eq 0) {
            $WriteTee.LastLogName = $null
        } else {
            foreach ($ExistingLog in $WriteTee.ExistingLogs) {
                try {
                    [IO.File]::OpenWrite($ExistingLog.FullName).close() | Out-Null
                    $WriteTee.LogFile = $ExistingLog.FullName
                    break
                } catch {
                    $WriteTee.LastLogName = $ExistingLog
                    continue
                }
            }
        }

        #If no previous logs can be added to create a new one.
        if (-not $WriteTee.ContainsKey('LogFile')) {
            switch ($WriteTee.LastLogName.Name) {
                {$_ -eq $Null} {
                    $WriteTee.ExistingLogs.count
                    Write-Host Create New File
                }
                {$_ -match '.*\[[0-9]+\]\.'} {
                    Write-Host AAAAAA
                    $WriteTee.NextLogName = $WriteTee.NextLogName.FullName.Split('[]')
                    $WriteTee.NextLogName = $WriteTee.NextLogName[0] + "[" + ([int]($WriteTee.NextLogName[1]) + 1) + "]" + $WriteTee.NextLogName[2]
                }
                default {}
            }
        }

        #Determine if log file is available or not.
        if ($WriteTee.ContainsKey('LogFile')) {
            Write-Host "Function Success"
            break
        } else {
            continue
        }
    }
    return $WriteTee.LogFile
}
clear
TestLogger

1 Ответ

0 голосов
/ 04 мая 2018

Я думаю, что я просто сгорел вчера, хороший ночной сон заставил меня снова пойти. вот что я закончил, очень надеюсь, что кто-то еще найдет в этом пользу.

Function TestLogger {
    $WriteTee = @{}
    $WriteTee.LogName  = 'WriteTee.log'
    #$WriteTee.LogName  = "$(((split-path -leaf $Script:MyInvocation.MyCommand.Definition)).BaseName).Log"
    $WriteTee.LogPaths = 'C:\Windows\',
                         "C:\Users\1151577373E\Documents\Powershell Scripts\AutoUpdater\",
                         "$Env:UserProfile"
                         #"$(split-path -parent $Script:MyInvocation.MyCommand.Definition)"


    Foreach ($Path in $WriteTee.LogPaths) {
        If ($WriteTee.ContainsKey('LogFile')) { Break }
        $Path = [System.IO.DirectoryInfo]$Path
        #Ensure the directory exists and if not, create it.
        If (![System.IO.Directory]::Exists($Path)) {
            Try {
                #Create the directory because .Net will error out if you try to create a file in a directory that doesn't exist yet.
                New-Item -Path $Path.Parent.FullName -Name $Path.BaseName -ItemType 'Directory' -ErrorAction Stop -Force |Out-Null
            } Catch {
                Continue
            }
        }#End-If

        #Check to see if there are any existing logs
        $WriteTee.ExistingLogs = Get-ChildItem -LiteralPath $Path -Filter "$(([System.IO.FileInfo]$WriteTee.LogName).BaseName)*$(([System.IO.FileInfo]$WriteTee.LogName).Extension)" |Sort-Object
        If ($WriteTee.ExistingLogs.Count -GT 0) {
            ForEach ($ExistingLog in $WriteTee.ExistingLogs) {
                Try {
                    [io.file]::OpenWrite($ExistingLog.FullName).close() |Out-Null
                    $WriteTee.LogFile = $ExistingLog.FullName
                    break
                } Catch {
                    $WriteTee.LastLogName = $ExistingLog
                    Continue
                }
            }
        }#End-If

        #If no previous logs can be added to create a new one.
        switch ($WriteTee.ExistingLogs.Count) {
            {$PSItem -EQ 0} {
                $WriteTee.TestLogFile = Join-Path -Path $Path -ChildPath $WriteTee.LogName
            }
            {$PSItem -EQ 1} {
                $WriteTee.TestLogFile = Join-Path -Path $Path -ChildPath ($WriteTee.LastLogName.basename + '[0]' + $WriteTee.LastLogName.Extension)
            }

            {$PSItem -GE 2} {
                $WriteTee.TestLogFile = $WriteTee.LastLogName.FullName.Split('[]')
                $WriteTee.TestLogFile = ($WriteTee.TestLogFile[0] + '[' + (([int]$WriteTee.TestLogFile[1]) + 1) + ']' + $WriteTee.TestLogFile[2])
            }
            Default {
                Write-Host "If you are looking for an explanation of how you got here, I can tell you I don't have one. But what I do have are a very particular lack of answers that I have aquired over a very long career that make these problems a nightmare for people like me."
                Continue
                }
        }#End-Switch

        #Last but not least, try to create the file and hope it is successful.
        Try {
            [IO.File]::Create($WriteTee.TestLogFile, 1, 'None').close() |Out-Null
            $WriteTee.LogFile = $WriteTee.TestLogFile
            Break
        } Catch {
            Continue
        }
    }#End-ForEach
    Return $WriteTee.LogFile

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...