Powershell 2.0:如何匹配或喜欢散列 table 键中的字符串
Powershell 2.0: how to -match or -like a string in hash table keys
对于 Powershell 2.0:
我有一个散列 table,其中有几个字符串作为键。与@{}.containskey
不同,是否可以使用通配符(例如"*xampl*"
)找到一个键(例如"examplekey"
)?
我设法完成了我想要的制作键列表并使用 Where-Object 作为过滤器的任务。但是有没有更简单的方法呢?我认为这种方法在我添加新键时特别糟糕,因为我每次都需要重新创建列表。
使用 .Keys
属性 和 -like
或 -notlike
运算符 return 键数组(或单个键):
if ($hash.keys -notlike '*xampl*') {
$hash.example = 1
}
将键存储在数组中以进行多次检查:
$keys = $hash.keys
if ($keys -notlike '*xampl*') {
$hash.example = 1
}
if ($keys -notlike '*foo*') {
$hash.example = 1
}
链接比较:
if ($hash.keys -notlike '*xampl*' -notlike '*123*') {
$hash.example = 1
}
或者如果有很多键并且您想执行很多检查,请使用正则表达式:
if ($hash.keys -join "`n" -match '(?mi)xampl|foo|bar|^herp\d+|\wDerp$|^and$|\bso\b|on') {
echo 'Already present'
} else {
$hash.foo123 = 'bar'
# ......
}
(?mi)
表示m多行大小写-i非敏感模式:每个键单独测试。
对于 Powershell 2.0:
我有一个散列 table,其中有几个字符串作为键。与@{}.containskey
不同,是否可以使用通配符(例如"*xampl*"
)找到一个键(例如"examplekey"
)?
我设法完成了我想要的制作键列表并使用 Where-Object 作为过滤器的任务。但是有没有更简单的方法呢?我认为这种方法在我添加新键时特别糟糕,因为我每次都需要重新创建列表。
使用 .Keys
属性 和 -like
或 -notlike
运算符 return 键数组(或单个键):
if ($hash.keys -notlike '*xampl*') {
$hash.example = 1
}
将键存储在数组中以进行多次检查:
$keys = $hash.keys
if ($keys -notlike '*xampl*') {
$hash.example = 1
}
if ($keys -notlike '*foo*') {
$hash.example = 1
}
链接比较:
if ($hash.keys -notlike '*xampl*' -notlike '*123*') {
$hash.example = 1
}
或者如果有很多键并且您想执行很多检查,请使用正则表达式:
if ($hash.keys -join "`n" -match '(?mi)xampl|foo|bar|^herp\d+|\wDerp$|^and$|\bso\b|on') {
echo 'Already present'
} else {
$hash.foo123 = 'bar'
# ......
}
(?mi)
表示m多行大小写-i非敏感模式:每个键单独测试。