Finding a variable text in another textfile and get the containing line

Hello there,

quite new to Powershell, i’m struggling with the following problem and im not finding any good answer in the interwebs.

I have a textfile “ID.txt” containing lines with IDs in form of “SBS1234568” in variable length.

I have another textfile “IPs.txt” containing lines with IP adresses and the mentioned ID above separated by “;” aka “ ; SBS1234568”

I now want to find IDs listet in “id.txt” in “IPs.txt” and get the entire line from “IPs.txt” to output it to another file.

I tried with a foreach and IF but I was not able to get it anywhere near…

This is what I tried so far:

$IPs = Get-Content IPs.txt
$ID = Get-Content ID.txt
Foreach ($line in $ID) {
IF (Select-String $IPs -Pattern "$line") {
$new_ip = $line | out-file -FilePath new_ips.txt;


Any help would be very much appreciated!

regards blitzdesigner

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.


you are right, sorry :slight_smile:

For completeness I am providing the same answer I shared on here.

You can use Select-String on the IPs.txt file but one important thing you’re missing is your text in ID.txt is in this format


Therefore when you’re trying to match a line in IPs.txt, it is effectively this

“ ; SBS1234568” -match “SBS1234568” # this is $false

You’d have to remove at least the first quote, but instead of doing all that I would treat it as a CSV.

$idfile    = New-TemporaryFile
$ipfile    = New-TemporaryFile
$newipfile = 'c:\temp\new_ips.txt'

'@ | Set-Content $idfile -Encoding utf8

" ; SBS1234568"
" ; SBS345689123"
" ; SBS87654"
" ; SBS87612354"
" ; SB612354"
'@ | Set-Content $ipfile -Encoding utf8

Import-Csv $idfile -Header id | foreach {
    (Select-String $ipfile -Pattern $
} | Set-Content $newipfile -Encoding utf8

Get-Content $newipfile


“ ; SBS1234568”
“ ; SBS345689123”
“ ; SBS87654”
“ ; SBS87612354”