当前位置: 移动技术网 > IT编程>脚本编程>Shell > PowerShell查找数组内容、搜索数组、查询数组的方法

PowerShell查找数组内容、搜索数组、查询数组的方法

2017年12月08日  | 移动技术网IT编程  | 我要评论

powershell中有-contain、-like、-in等操作符,使用这些操作符,可以很方便的在数组中查找元素内容。其中in操作符貌似要在powershell 3.0中才有。

先看一个例子,将windows目录的所有文件的文件名放入到数组$name中,然后在数组$name中查找exploer.exe元素。且看-contains的魅力!

复制代码 代码如下:

ps> $names = get-childitem -path $env:windir | select-object -expandproperty name
ps> $names -contains 'explorer.exe'
true

-contains操作符确实很强大,但是很遗憾,它不能在指定字符串中包含通配符。如果想使用通配符进行查找数组元素,则可以使用-like操作符。

复制代码 代码如下:

ps> $names -contains 'explorer*'
false

上面的例子说明了-contains不能使用通配符,下面我们来使用-like看看。
复制代码 代码如下:

ps> $names -like 'explorer*'
explorer.exe

文章一开头小编还说了,可以使用-in操作符来来作类似的处理,而且in操作符还可以将数组和要匹配的字符串反过来。什么意思呢?且看下面几个例子。
复制代码 代码如下:

ps> 'peter', 'mary', 'martin' -contains 'mary'
true
ps> 'peter', 'mary', 'martin' -contains 'ma*'
false
ps> 'mary' -in 'peter', 'mary', 'martin'
true
ps> 'peter', 'mary', 'martin' -like 'ma*'
mary
martin
ps> @('peter', 'mary', 'martin' -like 'ma*').count -gt 0

以上几个例子的含义,大家自行理解。关于使用powershell在数组中查找元素,小编就介绍这么多,希望对大家有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网