Reputation: 589
I have 2 text file like below
exclude.txt
10.1.1.3
10.1.1.4
10.1.1.5
10.1.1.6
free.txt
10.1.1.3
10.1.1.4
10.1.1.5
10.1.1.6
10.1.1.7
10.1.1.8
10.1.1.9
10.1.1.10
I want to write exclude the entries of exclude.txt from free.txt and write to another file
10.1.1.7
10.1.1.8
10.1.1.9
10.1.1.10
I tried :
compare-object (get-content $freeips) (get-content $excludeip) -PassThru | format-list | Out-File $finalips
Here in the final output I am always getting the first IP of the exclude.txt
10.1.1.7
10.1.1.8
10.1.1.9
10.1.1.10
10.1.1.3
and another way I tried
$exclude = Get-Content "C:\exclude.txt"
foreach($ip in $exclude)
{
get-content "C:\free.txt" | select-string -pattern $ip -notmatch | Out-File "C:\diff.txt"
}
But in this case also I am getting the entries of exclude.txt in the final output.
Please let me know where I am doing wrong here
Upvotes: 0
Views: 252
Reputation: 1
When comparing, $excludeip
should be the referenceObject and $freeips
comes after, like this:
compare-object (get-content $excludeip) (get-content $freeips) -PassThru | Out-File $finalips
Upvotes: 0
Reputation: 23673
The Select-String
solution is probably faster. Besides it doesn't require the iteration through the IP addresses as the -Pattern
parameters accepts a string array (String[]
). The point is thou that by default the pattern(s) repressent a regular expression where a dot (.
) is a place holder for any character. To search for a literal pattern you should use the -SimpleMatch
switch:
$exclude = Get-Content .\exclude.txt
get-content .\free.txt |Select-String -pattern $exclude -NotMatch -SimpleMatch
Note: The space in top of the displayed exclude.txt
file suggests that there might be an empty line in top of the file (which regex
matches any string). To get rid of any empty lines, use:
$exclude = Get-Content .\exclude.txt |Where-Object { $_ }
Upvotes: 1