powershell - 使用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

关于powershell - 使用powershell检查字符串列表中是否存在字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56930864/

相关文章:

PowerShell 的 Invoke-RestMethod 相当于curl -u(基本身份验证)

windows - Powershell - 使桌面背景更改立即生效

sql-server - 无法获取 SQL Server 服务信息 - WMI 问题?

powershell - 测试路径和 PATH 环境变量

arrays - PowerShell 如何将 Get-ChildItem 输出转换为字符串数组

powershell - 以编程方式批量删除 Azure Blob 存储对象

powershell - 对为什么必须在Windows上安装PowerShell Core感到困惑...?

powershell - 在具有提升权限的远程系统上运行Powershell脚本以启用远程处理

Powershell-将WebRequest调用到其中带有文字 '/'(%2F)的URL

multithreading - 写入单个日志文件的多线程中的Powershell代码,但是由于文件正在使用中而丢失了一些数据