Home > database >  find if the value present in text file values using powershell
find if the value present in text file values using powershell

Time:03-18

I have a list of Contract numbers in a text file.

185
166
504
506
507
510
509

I have servername like SERVER999AUTO1. I need to check if the number 999 present in the file. if present then, no operation else we have to perform certain operation.

I tried below, but for each contract it is printing the else value

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

Please let me know on this.

CodePudding user response:

Although a bit unclear, you can parse the value from the servername and look for it in the text file like so:

$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 details:

(?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)

CodePudding user response:

Continuing from my comment...

The reason why your else block is activated is because, your current iteration of the number you're on itself does not match "SERVER999AUTO1". You need to switch the order as "SERVER999AUTO1" matches "999", not the other way around:

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

Reversing the order to the correct order will work. In this case, I personally would use a switch statement as it can perform multiple conditions with a "cleaner" look:

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

... then again, it's all just preference.

  • Related