powershell - 使用powershell检查字符串列表中是否存在字符串
问题描述
我的环境中有 Powershell 版本 3,4 和 5。当我在下面编写代码时,它不断地给我错误,尽管 $CompatiableOS 包含 $OSverions 的输出。
[string] $CompatiableOS = '2016','2012','2008'
$OSVersion=[regex]::Matches(((Get-WmiObject -class Win32_OperatingSystem).caption), "([0-9]{4})")
if ( $CompatiableOS -contains $OSVersion)
{
return $TRUE
}
else
{
return $FALSE
}
但是当我将上面的代码更改为下面时,它起作用了。可能是什么问题?
[string] $CompatiableOS = '2016','2012','2008'
$OSVersion=[regex]::Matches(((Get-WmiObject -class Win32_OperatingSystem).caption), "([0-9]{4})")
if ( $CompatiableOS.contains($OSVersion))
{
return $TRUE
}
else
{
return $FALSE
}
解决方案
这经常出现。-contains 与 .contains()。他们非常不同。-contains 必须完全匹配。但是左边可以是一个字符串数组。实际上,您使用 [string] 演员将所有内容连接到左侧的一个字符串中。
$compatibleos
'2016 2012 2008'
'2016 2012 2008' -contains '2016'
False
'2016 2012 2008'.contains('2016')
True
'2016','2012','2008' -contains '2016'
True
('2016','2012','2008').contains('2016')
True
推荐阅读
- javascript - 如何动态创建字段并自动添加填充字段的值
- wpf - WinForms不同的WebView实例需要共享同一个会话
- c# - X509 证书预期用途和 SSL
- loopbackjs - 我可以在环回中的远程挂钩和操作挂钩之间传递数据吗?
- properties - 点符号的 QML 属性提示
- javascript - 为什么 window.scrollY !== document.body.clientHeight @ 最大滚动点
- java - 如何在 Inno Setup 的 PATH 中查找应用程序(Java)
- android - 为什么创建 android wear AVD 对我不起作用?
- c++ - 如果传递给 QGraphicsRectItem Qt c++,则更改光标
- javascript - 为什么我无法在 IOS Safari 中保存此二维码图像?