powershellpowercli

Powershell match similar entries in an array


I've written myself a script to check for vm-folders in vmware vcenter that dont match the corresponding vmname. There are a few automatically deployed VMs which i need to exclude from this check. Those VMs are always similarly named, but with an incremented number at the end. I've declared an array $Vmstoginrore containing strings of them and i'm trying to match my $VmName with this array but it does not work. Ive also tried it with like but i cannot seem to get this to work.

$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"
    }

Solution

  • The following code shows how to construct the regex programmatically from the given, literal array elements (VM name prefixes):

    # VM name prefixes to match.
    $Vmstoignore = @("Guest Introspection", "Trend Micro Deep Security")
    
    # Construct a regex with alternation (|) from the array, requiring
    # the elements 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 '|'
    
    # Sample input name.
    $VmName = "Guest Introspection (4)"
    
    # Now match the input name against the regex:
    # -> $true
    $VmName -match $regex
    

    Note: