-ErrorAction Stop在try/catch中失效,tabadmin ziplogs命令异常求助
tabadmin ziplogs PowerShell Script Issues Let’s walk through what’s happening with your script and fix each problem step by step:
1. Why -ErrorAction Stop triggers the help prompt
The -ErrorAction parameter is a PowerShell-specific common parameter built for native PowerShell cmdlets and functions. When you pass it to tabadmin (an external executable, not a PowerShell cmdlet), tabadmin doesn’t recognize it as a valid flag. This invalid argument causes the tool to spit out its help text instead of running the zip operation. That’s exactly why removing -ErrorAction Stop makes the command work again—you’re no longer passing an unrecognized parameter to tabadmin.
2. Why typos like zipylooog don’t trigger your catch block
PowerShell’s try/catch blocks only catch PowerShell-terminating errors by default (like failures from cmdlets using -ErrorAction Stop). External executables don’t throw PowerShell-style errors; they use exit codes to signal success or failure.
When you run a non-existent command like zipylooog, PowerShell throws a "command not found" error—but this is a non-terminating error by default, so it won’t trigger the catch block unless you adjust your error preference. For external tools like tabadmin, you need to check the exit code manually with $LASTEXITCODE instead of relying on try/catch alone.
Fixed Script Implementation
Here’s a revised version of your script that handles success and failure correctly, including triggering your backup email on errors:
# Run tabadmin ziplogs with your valid flags (no -ErrorAction Stop needed) tabadmin ziplogs -f -p -a -l -n # Check the exit code (0 = success, non-0 = failure for most Windows executables) if ($LASTEXITCODE -ne 0) { backupemail [System.Environment]::Exit(1) }
Key Improvements:
- Removed the incompatible
-ErrorAction Stopparameter - Uses
$LASTEXITCODEto validate the external command’s result (the standard way to check success/failure for non-PowerShell tools) - Ensures your backup email sends and the script exits with a failure code if
tabadminfails
Bonus: Catching "Command Not Found" Errors
If you want to also handle cases where tabadmin isn’t found (like your typo test), wrap the command in a try/catch with a temporary error preference adjustment:
# Save original error preference to restore later $originalErrorPref = $ErrorActionPreference $ErrorActionPreference = 'Stop' try { tabadmin ziplogs -f -p -a -l -n # Check if tabadmin ran but failed if ($LASTEXITCODE -ne 0) { throw "tabadmin failed with exit code $LASTEXITCODE" } } catch { backupemail [System.Environment]::Exit(1) } finally { # Reset to original error behavior $ErrorActionPreference = $originalErrorPref }
This version covers both scenarios: when tabadmin can’t be found at all, and when it runs but exits with a failure code.
内容的提问来源于stack exchange,提问作者Dave

