如何在powershell中过滤数组

How to filter array in powershell

我在 Powershell 中有一个包含一些字符串的数组,例如

$StringArray = {"all_srv_inf", "all_srv_inf_vir", "all_srv_inf_vir_vmw", "all_srv_rol", "all_srv_rol_iis", "all_srv_rol_dc"}

我想过滤数组中的所有字符串,所以只留下最独特的。

因此,在上面的示例中,我必须过滤 "all_srv_inf"、"all_srv_inf_vir" 和 "all_srv_rol",从而得到一个只有这些值的字符串数组:"all_srv_inf_vir_vmw", "all_srv_rol_iis" 和 "all_srv_rol_dc"

该列表实际上要长很多,所以过滤我的 Powershell 字符串数组的最有效方法是什么?

谢谢。

您的变量不包含实际数组,而是包含在调用时生成数组的脚本块。

过滤字符串的方法有很多种,你可以在SO或Google上搜索这里找到。您可以使用 Measure-Command { #your code } 尝试一些解决方案,看看需要多长时间并比较结果。

我的前两个想法是使用 -notmatch-notcontains/-notin-notmatch 使用通常更快的正则表达式,所以我将从它开始。根据您输入的数据等,另一种解决方案可能更适合您。因此您应该尝试不同的方法并对其进行衡量。

样本 -notmatch:

$StringArray = "all_srv_inf", "all_srv_inf_vir", "all_srv_inf_vir_vmw", "all_srv_rol", "all_srv_rol_iis", "all_srv_rol_dc"

#Build regex for items to exclude
$exclude = ('all_srv_inf', 'all_srv_inf_vir','all_srv_rol' | ForEach-Object { "^$([regex]::Escape($_))$" }) -join '|'

#Filter stringarray
$StringArray -notmatch $exclude