[英]Unable to catch the exception in try/catch statement in powershell
我正在尝试在if
语句中捕获异常-但即使条件失败, catch
不会引发任何异常
我在以下情况下尝试检查文件大小是否大于给定N
号-gt
。 如果条件有效,则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"
}
我需要获取所有失败案例的Expected catch语句。 我尝试了多种方法来获取catch异常,但没有任何效果。
赞赏是否有人可以帮助您。
正如Lee_Dailey在评论中提到的那样, catch
块仅在它“捕获”从前一try
块内部抛出的异常(或在PowerShell中为终止错误)时才执行。
返回$false
比较语句也不例外-gt
应该返回布尔值答案!
在你的情况下,只需添加else
块到if
语句会做, try/catch
并没有真正太大的意义:
# I changed the operator to `-ge` - aka. >= or "Greater-than-or-Equal-to"
# based on the assumption that `$Expected_count_of_file` is the minimum number expected
if($count_of_files.Count -ge $Expected_count_of_file) {
$existing_files
}
else {
# This only executes if the `if` condition evaluated to `$false`
Write-Error "Number of file is less"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.