【问题标题】:Adding Try/Catch on logging file path before script runs在脚本运行之前在日志文件路径上添加 Try/Catch
【发布时间】:2021-06-25 11:49:42
【问题描述】:

所以我有一个大脚本,如果无法进行日志记录,我需要添加一些功能来终止脚本。我的第一个想法是对日志文件路径进行尝试捕获...所以基本上如果无法到达日志文件的路径或无法写入路径中指定的目录,则正常退出。
我确信有更好的方法,但这是我能想到的最好的方法。现在实现这是一件苦差事,下面是一个截断的脚本块(我省略了 7 个函数的脚本块,以使下面的内容更短一些)。该部分中的代码不起作用..它实际上被忽略了,所以如果我故意在 $logfilepath 变量中输入错字,脚本无论如何都会愉快地运行。这与它应该做的相反。

<#
#---------------------------------------------------------[Initializations]-------------------------------------------------------- 
 Param (
[Parameter(Mandatory=$false)]
[Switch]$LogOnly
)

#  Dot Source required Function and config files
#. "\\server\scripts\Logging_Functions.ps1" 
. "c:\users\documents\powershell\Functions\Logging_Functions.ps1"
. "c:\users\documents\powershell\Litmos_Groups\config.txt"

#  Error Action
$ErrorActionPreference = 'silentlycontinue'
#  Debug preference
$global:DebugPreference = "continue"
#  WhatIf Preference, uncomment to run script in a logging only function
#$WhatIfPreference = $true

#----------------------------------------------------------[Declarations]----------------------------------------------------------
  
#  Script Version
$sScriptVersion = "1.0"

Import-Module ActiveDirectory


#----------------------------------------------------------[Functions]-------------------------------------------------------------


Function Get-DirectReport {...}

Function New-ReportToGroup {...}

Function New-ReportToGroup_logonly {...}

Function Get-DReports {...}

Function Set-RTGmembers {...}

Function Set-RTGmembers_logonly {...}

Function Remove-OOSGroups {...}

Function Remove-OOSGroups_logonly {...}

#----------------------------------------------[ Execution ]------------------------------------------------
# Below checks for logpath viability    
if (-not (Test-path -Literalpath $sLogFile)) {
        try {
            " " | set-content -encoding utf8 -literalpath $sLogFile -erroraction Stop
            }
        Catch {
            Write-Eventlog -logname 'Application' -Source 'PS_Scripts' -EntryType Error -EventId 8675 -Message "Set-LitmosGroups5 encountered an error. LogPath not reachable or log file not found"
            -ExitGracefully $True
            Break
        }
    }
    
    Foreach ($Manager in $Managers) {
        if (-not $LogOnly) {
        $Directreports = Get-Directreport $manager -norecurse  | Select-Object -expand samAccountName
        $script:AddUserCount += ($DirectReports | Measure-Object).count
        $time = (Get-Date).ToString('T')
            New-ReportToGroup
            Get-DReports
            Set-RTGmembers
            Log-Write -LogPath $sLogFile -LineValue "Direct reports are: $Directreports"
            Log-Write -LogPath $sLogFile -LineValue "========================[$Time ]==============================="
            
     } else {
            $script:LOAddUserCount += ($DirectReports | Measure-Object).count
            New-ReportToGroup_logonly
            Get-DReports
            Set-RTGmembers_logonly
            Log-Write -LogPath $sLogOnlyFile -LineValue "========================[ LogOnly ]==============================="  
        }
      }
    Foreach ($Report in $ReportsTo) {
        If (-not $LogOnly){
        Remove-OOSGroups
    } else {
        Remove-OOSGroups_logonly
            }
       }
    
    if (-not $LogOnly) {
        Log-Write -Logpath $sLogPath -Linevalue "$AddUserCount Total users matched"
        Log-Write -LogPath $sLogPath -Linevalue "$AddGroupCount New groups added"
        Log-Write -LogPath $sLogPath -Linevalue "$GroupsRemoved groups removed"
        Log-Write -LogPath $sLogPath -Linevalue "====[END]====="
    } else {
        Log-Write -Logpath $sLogOnlyPath -Linevalue "$LOAdduserCount Users who would be added"
        Log-Write -Logpath $sLogOnlyPath -Linevalue "$LOGroupCount Groups that would be added"
        Log-Write -LogPath $sLogOnlyPath -Linevalue "$LOGroupsRemoved Groups that would be removed"
        Log-Write -LogPath $sLogOnlyPath -Linevalue "====[END]====="
    }

【问题讨论】:

  • 你的问题我不清楚。你是说[ Execution ] 部分中的代码仍然运行,即使$LogFile 无效(即Test-path -Literalpath $sLogFile 返回false?
  • -ExitGracefully $Truecatch 块中间做什么?你是想写exit 0 还是return
  • @MathiasR.Jessen 我在一个随机博客上发现了该块,其中该人试图做一些与我想要的“相似”的事情。我假设如果触发了“catch”,那么这将允许脚本优雅地退出。然后我添加了一些关于尝试在事件日志中吐出一些关于它的内容。
  • 如果您的 $ErrorActionPreference 是 'silentlycontinue',您不能期望捕获任何错误。
  • 我没有部分理解某些东西,我知道错误是什么。我鼓励你阅读这篇完整的文章adamtheautomator.com/powershell-try-catch

标签: powershell scripting try-catch


【解决方案1】:

所以我不会说这些人没有帮助,尤其是 @santiagosquarzon 取消注释我的 ErrorActionpreference 的建议。但是我正在寻找的解决方案是将我的 foreach 循环封装在 $sLogPath 的 if/else 中。 If/Elses,ForEach ......它们很容易在我的脑海中扭曲。 所以是这样的:

if (test-path $sLogPath) {
     
    Foreach ($Manager in $Managers) {
        if (-not $LogOnly) {
       $Directreports = Get-Directreport $manager -norecurse  | Select-Object -expand samAccountName
       $script:AddUserCount += ($DirectReports | Measure-Object).count
        $time = (Get-Date).ToString('T')
          New-ReportToGroup
          Get-DReports
          Set-RTGmembers
          Log-Write -LogPath $sLogFile -LineValue "Direct reports are: $Directreports"
          Log-Write -LogPath $sLogFile -LineValue "========================[$Time ]==============================="
        
    } else {
        $script:LOAddUserCount += ($DirectReports | Measure-Object).count
        New-ReportToGroup_logonly
        Get-DReports
        Set-RTGmembers_logonly
        Log-Write -LogPath $sLogOnlyFile -LineValue "========================[ LogOnly ]==============================="  
    }
  }

  else {
       Write-Eventlog -logname 'Application' -Source 'PS_Scripts' -EntryType Error -EventId 8675 -Message "Set-LitmosGroups5 encountered an error. LogPath not reachable or log file not found"
       write-host "True"
       Return
    }
Foreach ($Report in $ReportsTo) {
     If (-not $LogOnly){
     Remove-OOSGroups
  } else {
     Remove-OOSGroups_logonly
     }
 }

 if (-not $LogOnly) {
   Log-Write -Logpath $sLogPath -Linevalue "$AddUserCount Total users matched"
   Log-Write -LogPath $sLogPath -Linevalue "$AddGroupCount New groups added"
   Log-Write -LogPath $sLogPath -Linevalue "$GroupsRemoved groups removed"
   Log-Write -LogPath $sLogPath -Linevalue "====[END]====="
} else {
    Log-Write -Logpath $sLogOnlyPath -Linevalue "$LOAdduserCount Users who would be added"
    Log-Write -Logpath $sLogOnlyPath -Linevalue "$LOGroupCount Groups that would be added"
    Log-Write -LogPath $sLogOnlyPath -Linevalue "$LOGroupsRemoved Groups that would be removed"
    Log-Write -LogPath $sLogOnlyPath -Linevalue "====[END]====="
  }

}

【讨论】:

    猜你喜欢
    • 2019-04-17
    • 1970-01-01
    • 2021-07-08
    • 2018-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多