powershell - 如果 Else 语句在使用 PowerShell 的 Else 端不起作用
问题描述
我在我的 powershell 脚本中使用 if else 。
if ($match.Groups.Count) {
while ($match.Success) {
Write-Host ("Match found: {0}" -f $match.Value)
$match = $match.NextMatch()
}
}
else {
Write-Host "Not Found"
}
在 if 方面,它可以工作,但在 else 方面,它不能返回 "Not Found" 。它没有显示任何错误。
解决方案
PetSerAl就像以前无数次一样,在评论中提供了关键指针:
也许令人惊讶的[System.Text.RegularExpressions.Match]
是,静态[regex]::Match()
方法(或其对应的实例方法)返回的实例在其属性中包含 1 个元素,.Groups
即使匹配操作没有成功[1],因此,假设存储在 中的$match
实例$match.Groups.Count
总是返回$true
。
相反,使用该.Success
属性来确定是否找到了匹配项,就像您在while
循环中所做的那样:
if ($match.Success) {
while ($match.Success) {
"Match found: {0}" -f $match.Value
$match = $match.NextMatch()
}
} else {
"Not Found"
}
请注意,我已经删除了Write-Host
调用,因为 Write-Host
通常使用错误的工具,除非意图明确写入仅显示,从而绕过 PowerShell 的输出流,从而绕过将输出发送到其他命令的能力,将其捕获变量或将其重定向到文件。
[1][regex]::Match('a', 'b').Groups.Count
返回1
,即使匹配显然没有成功。
推荐阅读
- sql - CASE WHEN 来自没有子查询的嵌套 CASE WHEN?
- java - 在命令行中编译 Intellij-Project
- javascript - “浏览器”的区别。和“信使”。使用 webextension/javascript API 时
- python - 如何防止嵌套列表被 Python 的 csv.reader 解析为字符串?
- python - Flask - 回传内部请求的响应
- python-3.x - 检查networkx中两个节点之间图的长度(权重)的功能是什么?
- python - 从列表中删除所有实例
- jenkins - 如何在 Jenkins Pipeline 中引用 Maps 变量的映射
- sharepoint - 使用 Microsoft Graph 按查找 ID 获取 SharePoint 用户
- php - 将待处理队列从 Redis 移动到数据库 - Laravel