在脚本运行之前在日志文件路径上添加 Try/Catch

Adding Try/Catch on logging file path before script runs

所以我有一个大脚本,我需要添加一些功能来在无法进行日志记录时终止脚本。我的第一个想法是在日志文件路径上尝试捕获...所以基本上如果无法到达日志文件的路径或者无法写入路径中指定的目录,那么就优雅地退出。
我确信有更好的方法,但这是我能想到的最好的方法。现在实现它一直是一件苦差事,下面是一个截断的脚本块(我省略了 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]====="
    }

所以我不会说这些人没有帮助,尤其是@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]====="
  }

}