我在文本文件中有一个合同编号的列表。
185
166
504
506
507
510
509我有像SERVER999AUTO1.一样的服务器名我需要检查文件中是否存在999。如果现在就没有手术,否则我们就得做一定的手术。
我在下面尝试过,但是对于每一份合同,它都是打印其他值。
$file = Get-Content "C:\list.txt"
$containsWord = $file | %{$_ -match "SERVER999AUTO1"}
if ($containsWord -contains $true) {
Write-Host "There is!"
} else {
Write-Host "There ins't!"
}请告诉我这件事。
发布于 2022-03-17 13:02:16
虽然有点不清楚,但您可以解析来自servername的值,并在文本文件中查找它,如下所示:
$serverName = 'SERVER999AUTO1'
$valueISeek = ([regex]'(?i)server(\d+).*').Match($serverName).Groups[1].Value
if ((Get-Content "C:\list.txt") -contains $valueISeek) {
Write-Host "Value '$valueISeek' found!" -ForegroundColor Green
} else {
Write-Host "Value '$valueISeek' could not be found!" -ForegroundColor Red
}Regex详细信息:
(?i) Match the remainder of the regex with the options: case insensitive (i)
server Match the characters “server” literally
( Match the regular expression below and capture its match into backreference number 1
\d Match a single digit 0..9
+ Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
. Match any single character that is not a line break character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)发布于 2022-03-17 13:51:02
继续我的评论..。
激活else块的原因是,您当前正在进行的数字迭代本身与"SERVER999AUTO1“不匹配。您需要在"SERVER999AUTO1“与"999”匹配时切换订单,而不是反过来:
$file = Get-Content "C:\list.txt"
$containsWord = $file | %{"SERVER999AUTO1" -match $_}
if ($containsWord -contains $true) {
Write-Host "There is!"
} else {
Write-Host "There ins't!"
}将订单倒转到正确的顺序是可行的。在本例中,我个人将使用switch语句,因为它可以使用“更干净”的外观来执行多个条件:
$toMatch = "SERVER999AUTO1"
switch -File ("C:\list.txt")
{
{$toMatch -match $_} { "There is!"; Break }
default {"There isn't" }
}..。再说一遍,这都只是偏好。
https://stackoverflow.com/questions/71511683
复制相似问题