【问题标题】:Powershell match similar entries in an arrayPowershell 匹配数组中的相似条目
【发布时间】:2022-08-18 21:59:54
【问题描述】:

我为自己编写了一个脚本来检查 vmware vcenter 中与相应 vmname 不匹配的 vm 文件夹。 有一些自动部署的虚拟机我需要从这项检查中排除。这些虚拟机的名称总是相似的,但最后会增加一个数字。我已经声明了一个包含它们的字符串的数组 $Vmstoginrore,并且我试图将我的 $VmName 与这个数组匹配,但它不起作用。我也试过了,但我似乎无法让它工作。

$Vmstoignore=@( \"Guest Introspection\",\"Trend Micro Deep Security\")
$VmName = \"Guest Introspection (4)\"

    if ($Vmstoignore-match $VmName ){
        Write-Output \"does match\"
    }
    else {
        Write-Output \"doesn\'t match\"
    }

    标签: powershell powercli


    【解决方案1】:
    • 从 v7.2.x 开始,PowerShell 提供接受一个比较运算符大批比较值(仅输入操作数可以是一个数组)。

    • 但是,正弦 -match operator 是基于 regex 的,您可以使用带有交替 (|) 的单个正则表达式来匹配模式。

    以下代码构造正则表达式以编程方式从给定的文字数组元素(VM 名称前缀):

    $Vmstoignore = @( "Guest Introspection", "Trend Micro Deep Security")
    
    # Construct a regex with alternation (|) from the array, requiring
    # each element to match at the *start* (^) of the input string.
    # The resulting regex is:
    #    ^Guest\ Introspection|^Trend\ Micro\ Deep\ Security
    $regex = $Vmstoignore.ForEach({ '^' + [regex]::Escape($_) }) -join '|'
    
    $VmName = "Guest Introspection (4)"
    
    # -> $true
    $Vmstoignore -match $regex
    

    【讨论】:

      【解决方案2】:

      -match 用于正则表达式模式比较,您可以使用-eq$a.equals($b) 进行字符串比较,或者使用-like 运算符将字符串匹配到通配符模式。

      结帐this SO postthe Microsoft documentation

      function Contains-SubString() {
          param (
              [string[]]$strings,
              $target
          )
      
          foreach($string in $strings) {
              if($target -like "*$($string)*") {
                  return $true
              }
          }
      
          return $false
      
      }
      
      [string[]]$Vmstoignore=@( "Guest Introspection","Trend Micro Deep Security")
      $Vmstoignore.Count
      $VmName = "Guest Introspection (4)"
      
      if (Contains-SubString -strings $Vmstoignore -target $VmName ){
          Write-Output "does match"
      }
      else {
          Write-Output "doesn't match"
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多