当我从新打开的PowerShell控制台运行以下脚本时,循环会退出,因此显然存在匹配,但$matches变量(因此$matches.PORT(并不是第一次填充的。当脚本再次运行时,它将被填充。
/ssh.ps1
$BLOCK = { az webapp create-remote-connection --subscription <MY-SUBSCRIPTION> --resource-group <RESOURCE-GROUP> -n <NAME> }
$global:CONNECTION = Start-ThreadJob -ScriptBlock $BLOCK
$done = 0
$match_string = ".*Opening tunnel on port: (?<PORT>d{1,5})b.*"
while ($done -lt 1) {
if ($CONNECTION.HasMoreData)
{
$DATA = Receive-Job $CONNECTION 2>&1
if ($DATA -match $match_string)
{
$port = $matches.PORT
Write-Output "Connection open on port $port."
$done = 1
}
}
}
Write-Output "Loop ended."
exit
PowerShell控制台中的输出为:
PS <LOCAL-DIR>> ./ssh
Connection open on port .
Loop ended.
PS <LOCAL-DIR>> ./ssh
Connection open on port 63182.
Loop ended.
相比之下,当我尝试运行以下脚本时,第一次运行时会填充$matches。
/match.ps1
$string1 = "hello, hello, you big beautiful world of wonder!"
$match_str = ".*b(?<gotcha>world)b.*"
$done = 0
while ($done -lt 1)
{
if ($string1 -match $match_str)
{
write-output "Matches:"
write-output $matches
$done = 1
}
}
输出:
PS <LOCAL-DIR>> ./match
Matches:
Name Value
---- -----
gotcha world
0 hello, hello, you big beautiful world of wonder!
如果有人能理解为什么第一个脚本中的文本是匹配的,而没有填充$matches,我将不胜感激。
p.S。循环后存在的脚本只是为了调查目的,而不是我的代码实际会做什么
p.p.S。作为参考,az webapp create-remote-connection
在连接时延迟后的输出为:
Verifying if app is running....
App is running. Trying to establish tunnel connection...
Opening tunnel on port: 63341
SSH is available { username: root, password: Docker! }
Ctrl + C to close
(端口每次都不同。(
如果在-match
操作后未填充自动$Matches
变量,则意味着LHS操作数是集合,而不是单个字符串。
因此,循环$DATA
的值,并单独匹配每一行:
foreach ($line in $DATA) {
if ($line -match $match_string)
{
$port = $matches.PORT
"Connection open on port $port."
$done = 1
break
}
}
按设计:
只有当LHS是字符串(标量(时,才会填充$Matches
- 以集合(数组(作为LHS,
-match
(与许多比较运算符一样(充当过滤器,并返回匹配元素的(可能为空(子数组 - 任何先前的
$Matches
值都被保留,如果给定的字符串标量-match
操作恰好找不到匹配或其LHS是集合