Partial string match on a list

This topic contains 1 reply, has 2 voices, and was last updated by  Dave Wyatt 3 years, 7 months ago.

  • Author
    Posts
  • #15116

    Simon Holman
    Participant

    I am using the script from http://cloudtidings.com/2010/08/03/dpm-2010-powershell-script-to-auto-protect-vms-as-they-get-added-to-a-csv-cluster/ to auto add new VM's to my DPM Protection Group.

    I need to have a list of VM's to exclude from being auto added to the group.

    Outside this section

    foreach ($ds in $unprotectedDSList)
    {
    write-host "Adding data source" $ds.Name "to" $MPG.FriendlyName
    $npg = Add-ChildDatasource -ProtectionGroup $MPG -ChildDatasource $ds

    # 12.1 Disk Allocation is skipped in case of short term protection being to tape.
    if($MPG.protectionmethod -eq $tape) {continue;}
    $x = Get-DatasourceDiskAllocation -Datasource $ds
    Set-DatasourceDiskAllocation -Datasource $ds -ProtectionGroup $MPG
    }

    I need to have a list of servers (something like $VMsToIgnore = @("SQL01", "EXCH01")) and test them against $ds.Name within the loop to see if there's a match. The trouble is that $ds.Name may be "Offline\EXCH01" or "Online\EXCH01" so I can't do a direct -compare against my list.

    How would I do the check?

  • #15117

    Dave Wyatt
    Moderator

    There are several ways. One approach I've used for this kind of thing in the past is to convert the array into a single regex, which can be used with the -match or -notmatch operators:

    $VMsToIgnore = @('SQL01', 'EXCH01') 
    $pattern = ($VMsToIgnore | ForEach-Object { [regex]::Escape($_) }) -join '|'
    
    foreach ($ds in $unprotectedDSList)
    {
        if ($ds.Name -match $pattern) { continue }
        # ... do other stuff
    }
    

    You could also use wildcard patterns and the -like operator, something like this:

    $VMsToIgnore = @('*SQL01*', '*EXCH01*') 
    
    foreach ($ds in $unprotectedDSList)
    {
        if ($VMsToIgnore | Where-Object { $ds.Name -like $_ }) { continue }
        # ... do other stuff
    }
    

You must be logged in to reply to this topic.