我正在处理一个脚本,用于将数据库的架构备份到版本控制系统。我只是意识到复制的对象也被脚本化了。这些对象以sp_MSupd_,sp_MSdel_,sp_MSins_和syncobj_0x开头。我想跳过这些项目。
我知道我可以做这样的事情:
$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
If ($ExcludeObjectNames -contains "sp_MSdel_SampleObject")
{
Write-Host "replicated item found"
}
但这仅适用于完全匹配。我尝试将*添加到数组中的元素,但这没有用。而且我知道我可以使用-like,但这似乎仅用于单个值,而不是数组。
我知道我可以做到
$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"
}
这很好,但是,如果我发现越来越多的事情要忽略,那就变得越来越丑陋。
是否可以在数组上使用带有-contains的通配符?
答案 0 :(得分:2)
$ExcludeObjectNames = @("sp_MSupd_", "sp_MSdel_","sp_MSins_","syncobj_0x")
Foreach ($ExcludeObjectName in $ExcludeObjectNames) {
If ("sp_MSdel_SampleObject" -match $ExcludeObjectName)
{
Write-Host "replicated item found"
}
}
或者,如果您只想在脚本中编辑变量,则可以执行以下操作:
$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"
}
}
如果您不喜欢循环,则可以从原始数组中构建一个正则表达式过滤器:
$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"
}