Tech_Spaniard
Tech_Spaniard

Reputation: 1

Using a variable within a PowerShell Select-String

I have this one section of my PowerShell script that I'm currently stuck on. Basically, I have two files that I want to do a comparison on via select-string...In detail

For each item in FileA.txt I want to do a select-string to FileB.txt to discover if it exist. If the line item in FileA.txt doesn't exist in FileB.txt, then print the FileA.txt line item to the screen.

This is what the text files looks like..more or less

FileA.txt

1
2
3
4
6

FileB.txt

6
7
8
9
10

Desired output would be the following:

1
2
3
4

This is what my PS code looks like now. My thought process was that I could use the variable within the select-string but its not working out for me :(

$IPs = Get-Content "C:\\FileA.txt" 

Get-Content C:\FileB.txt | Select-String -InputObject $IPs

Could someone please help me out and point out what I am doing wrong.

Upvotes: 0

Views: 853

Answers (2)

Mike Zboray
Mike Zboray

Reputation: 40838

In this specific example, Compare-Object would probably be a better choice. It is designed to find the differences between two lists.

You would use something like:

Compare-Object -ReferenceObject $(gc .\FileA.txt) -DifferenceObject $(gc .\FileB.txt) | where { $_.SideIndicator -eq '<=' } | select -expand InputObject

However, you could also do this with select-string:

gc .\FileA.txt | select-string -Pattern $(gc .\FileB.txt) -NotMatch

which just finds the lines of FileA that don't match the lines of FileB, however the lines of FileB are interpreted as regular expressions, which probably isn't appropriate for IP addresses since '.' is a wildcard.

Upvotes: 2

sodawillow
sodawillow

Reputation: 13176

Based on your limited sample data, here is an example of how you could do this :

"1 2 3 4 6" > "fileA.txt"
"6 7 8 9 10" > "fileB.txt"

$arrayA = (Get-Content "fileA.txt").Split(" ")
$arrayB = (Get-Content "fileB.txt").Split(" ")

$arrayResult = @()

foreach($valueA in $arrayA) {
    if($arrayB -notcontains $valueA) {
        $arrayResult += $valueA
    }
}

$arrayResult -join " "

Now I believe the input files will be quite different eventually

EDIT :

Using line breaks :

"1
2
3
4
6" > "fileA.txt"

"6
7
8
9
10" > "fileB.txt"

$arrayA = Get-Content "fileA.txt"
$arrayB = Get-Content "fileB.txt"

$arrayResult = @()

foreach($valueA in $arrayA) {
    if($arrayB -notcontains $valueA) {
        $arrayResult += $valueA
    }
}

$arrayResult -join "`n"

NB : the 2 scripts begin by filling the needed files, I guess you won't need to do it

Upvotes: 2

Related Questions