UnhandledExcepSean
UnhandledExcepSean

Reputation: 12804

How can I use wildcards with IF -contains on an array?

I'm working on a script backing up the schema for a database to a version control system. I just realized that replicated objects are being scripted out as well; these objects start with sp_MSupd_, sp_MSdel_, sp_MSins_, and syncobj_0x. I would like to skip these items.

I know I can do something like this:

$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
If ($ExcludeObjectNames -contains "sp_MSdel_SampleObject")
{
    Write-Host "replicated item found"
}

But this only works for exact matches. I tried adding * to the elements in the array but that did not work. And I know I can use -like, but that seems to only be for single values, not arrays.

I know I can do this

$ObjectNames = "sp_MSdel_SampleObject"
If ($ObjectNames -like "sp_MSupd_*" -OR $ObjectNames -like "sp_MSdel_*" -OR $ObjectNames -like "sp_MSins_*" -OR $ObjectNames -like "syncobj_0x*")
{
    Write-Host "replicated item found"
}

This is well and fine, BUT if I find more and more things to omit, this becomes more and more ugly.

Is there a way to use wildcards with -contains on an array?

Upvotes: 0

Views: 68

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")

Foreach ($ExcludeObjectName in $ExcludeObjectNames) {
  If ("sp_MSdel_SampleObject" -match $ExcludeObjectName)
  {
      Write-Host "replicated item found"
  }
}

Or if you only want to edit variables in the script, you can do:

$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
$ObjectToCheck = "sp_MSdel_SampleObject" # This variable contains your original contains target

Foreach ($ExcludeObjectName in $ExcludeObjectNames) {
  If ($ObjectToCheck -match $ExcludeObjectName)
  {
      Write-Host "replicated item found"
  }
}

If you don't like looping, you can just build a regex filter from your original array:

$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
$ObjectToCheck = "sp_MSdel_SampleObject" # This variable contains your original contains target
$excludeFilter = '(^' + ($excludeobjectnames -join "|^") + ')' # Regex filter that you never have to manually update

If ($ObjectToCheck -match $ExcludeFilter)
{
    Write-Host "replicated item found"
}

Upvotes: 2

Related Questions