gpt4 book ai didi

powershell - 用于检测重复的主机名的PowerShell脚本-但仅主机名的一部分

转载 作者:行者123 更新时间:2023-12-03 00:24:01 25 4
gpt4 key购买 nike

如果我有主机名的列表(csv,txt,数组等),例如:

abc123Aaab123Bbcd123Cdef123Aabb123Babb123Aabb123B

How can I make sure the first 3 letters (site code) have only 1 instance/host in the array or list? I don't need any of the other hosts at a site, just one host from each unique site to represent my final list

$A = $(foreach ($line in Get-Content C:\Test1\File1.txt) {$line.tolower().split(" ")}) | sort | Get-Unique
$A.count

上面的代码本质上仅查找重复项-我可以指定以某种方式查看的前三个字母吗?

提前致谢

最佳答案

你是这个意思吗?

@("abc123A",
"aab123B",
"bcd123C",
"def123A",
"abb123B",
"abb123A",
"abb123B") | select @{ Name = 'Site'; Expression = {$_.SubString(0,3)}} | Select-Object -Property Site -Unique

这将产生以下结果:
Site                                                                                                                                                                                                                                                             
----
abc
aab
bcd
def
abb

它使用计算所得的属性从列表中选择前三个字母。

如果要查看分组,可以使用以下方法:
select @{ Name = 'Site';  Expression = {$_.SubString(0,3)}}, @{ Name = 'Host';  Expression = {$_}} | Group-Object -Property Site

会产生以下结果:
Count Name                      Group                                                                                                                                                                                                                            
----- ---- -----
1 abc {@{Site=abc; Host=abc123A}}
1 aab {@{Site=aab; Host=aab123B}}
1 bcd {@{Site=bcd; Host=bcd123C}}
1 def {@{Site=def; Host=def123A}}
3 abb {@{Site=abb; Host=abb123B}, @{Site=abb; Host=abb123A}, @{Site=abb; Host=abb123B}}

如果您只想从每个“站点”中选择一个“主机”,则从每个组中选择第一个,如下所示:
select @{ Name = 'Site';  Expression = {$_.SubString(0,3)}}, @{ Name = 'Host';  Expression = {$_}} | Group-Object -Property Site | %{$_.Group[0].Host} 

这会给你这个:
abc123A
aab123B
bcd123C
def123A
abb123B

关于powershell - 用于检测重复的主机名的PowerShell脚本-但仅主机名的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50950361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com