当前位置: 动力学知识库 > 问答 > 编程问答 >

powershell - Remove String in one text file from another text file

问题描述:

I have two text files. One has all servers on the domain (servers_all.txt) and the other has only the virtual servers (virtual_servers.txt). I want to get the difference between the two so I can find the physical servers. I have been tring compare-object to no avail

Compare-Object (gc servers_all.txt) (gc .\VIRTUAL_SERVERS.TXT) -IncludeEqual

Is there a way I can remove the servers listed in virtual_servers.txt from servers_all.txt.

Both txt files are formatted the same way with only the server names in a single column ie:

ServerA

ServerB

ServerC

网友答案:

Compare-Object is somewhat obtuse (to put it mildly). I avoid it.

$VirtualServers = Get-Content .\VIRTUAL_SERVERS.TXT;
$NonVirtualServers = Get-Content servers_all.txt | Where-Object { $_ -notin $VirtualServers };

The only thing to beware of here is file formatting errors like leading or trailing whitespace. If you want to handle that, you could do something like:

$VirtualServers = Get-Content .\VIRTUAL_SERVERS.TXT | ForEach-Object { $_.Trim() };
$NonVirtualServers = Get-Content servers_all.txt | ForEach-Object { $_.Trim() } | Where-Object { $_ -notin $VirtualServers };
网友答案:
$all = 'a','b','c','d'
$virtual = 'b','c'

Compare-Object $all $virtual -PassThru

->

a
d
分享给朋友:
您可能感兴趣的文章:
随机阅读: