【发布时间】:2019-12-17 20:35:46
【问题描述】:
我试图在 if 语句中捕获异常 - 但 catch 即使条件失败也不会抛出任何异常
我有以下情况,我试图检查文件大小是否为-gt 而不是给定的N 数字。如果条件有效,则try 部分正在执行,但即使条件错误,catch 部分也不会抛出任何错误
$source_dir="C:\test_files_arch"
$Existing_count_of_files=Get-ChildItem $source_dir | Measure-Object | Select-Object Count
$existing_files= ls $source_dir
$Expected_count_of_file=5
#Assuming the Existing_count_of_files is 4, so it should failed
try {
if($count_of_files.Count -gt $Expected_count_of_file) {
$existing_files
}
}
catch {
Write-Error "Number of file is less"
}
我需要获取所有失败案例的预期 catch 语句。我尝试了很多方法来获取捕获异常,但没有任何效果。
感谢任何人可以提供帮助。
【问题讨论】:
-
TRY/CATCH/FINALLY 东西需要 - 需要 - 一个终止错误。你根本没有任何东西会在你的代码的任何部分触发这样的错误——它必须在
try部分。 [咧嘴] -
谢谢@Lee_Dailey。在我包含 finally 语句后,它就起作用了
-
不客气 [grin] ...但是您没有正确使用 try/catch/finally,尽管如此。 [皱眉] 你没有发现任何错误。您只是添加了运行
try然后运行finally块并且根本没有错误处理的无意义代码。就目前而言,您有一个非常奇怪的脚本块。我会完全删除无意义的代码或重写它以实际进行错误处理。
标签: powershell exception error-handling