首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用powershell查找文本文件值中的值是否存在

使用powershell查找文本文件值中的值是否存在
EN

Stack Overflow用户
提问于 2022-03-17 11:38:48
回答 2查看 60关注 0票数 0

我在文本文件中有一个合同编号的列表。

代码语言:javascript
复制
185
166
504
506
507
510
509

我有像SERVER999AUTO1.一样的服务器名我需要检查文件中是否存在999。如果现在就没有手术,否则我们就得做一定的手术。

我在下面尝试过,但是对于每一份合同,它都是打印其他值。

代码语言:javascript
复制
$file = Get-Content "C:\list.txt"
$containsWord = $file | %{$_ -match "SERVER999AUTO1"}
if ($containsWord -contains $true) {
    Write-Host "There is!"
} else {
    Write-Host "There ins't!"
}

请告诉我这件事。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-03-17 13:02:16

虽然有点不清楚,但您可以解析来自servername的值,并在文本文件中查找它,如下所示:

代码语言:javascript
复制
$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详细信息:

代码语言:javascript
复制
(?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)
票数 3
EN

Stack Overflow用户

发布于 2022-03-17 13:51:02

继续我的评论..。

激活else块的原因是,您当前正在进行的数字迭代本身与"SERVER999AUTO1“不匹配。您需要在"SERVER999AUTO1“与"999”匹配时切换订单,而不是反过来:

代码语言:javascript
复制
$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语句,因为它可以使用“更干净”的外观来执行多个条件:

代码语言:javascript
复制
$toMatch = "SERVER999AUTO1"
switch -File ("C:\list.txt")
{
    {$toMatch -match $_} { "There is!"; Break }
    default {"There isn't" }
}

..。再说一遍,这都只是偏好。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71511683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档