powershell - 无法在 powershell 的 try/catch 语句中捕获异常
问题描述
我试图在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 语句。我尝试了很多方法来获取捕获异常,但没有任何效果。
感谢是否有人可以提供帮助。
解决方案
正如 Lee_Dailey 在评论中提到的,该块仅在它“捕获”从前一个块内部抛出catch
的异常(或者,在 PowerShell 中,一个终止错误)时才会执行。try
$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"
}
推荐阅读
- macos - 在 macOS 中找不到 Python.h 编译 C 程序
- python - 在 Python 中对列表/文件进行排序
- r - 移动数据框列
- python - 由于目录错误,Python 找不到我的文件
- python - 如何有效地计算 Dask/xarray 中轴中值的第一个实例?
- doctrine-orm - Symfony 使用外键查询数据库
- powershell - 如何在powershell中对hastable属性执行where-object?
- python - 从整数字符串返回最大值和最小值
- javascript - 联系表格不发送电子邮件,问题代码?
- url - SSRS Action Expression - 使用字段值作为 url 打开一个新页面