I would like to Pester to check if a public IP is attached to either $edge00
or $edge01
NIC
# id of the Get-AzPublicIpAddress output will = "/subscriptions/asdf-asdf-asdf/resourceGroups/RG-ASDF-FW/providers/Microsoft.Network/networkInterfaces/FW-ASDF-EDGE-00-NIC1/ipConfigurations/FW-ASDF-EDGE-ASDF"
$edge00 = "FW-ASDF-EDGE-00-NIC1"
$edge01 = "FW-ASDF-EDGE-01-NIC1"
# this will fail
(Get-AzPublicIpAddress -Name "PIP-FW-ASDF-EDGE-UNTRUST" -ResourceGroupName "RG-ASDF-FW").IpConfiguration.Id | Should -Match ($edge00 -or $edge01)
# this will work
(Get-AzPublicIpAddress -Name "PIP-FW-ASDF-EDGE-UNTRUST" -ResourceGroupName "RG-ASDF-FW").IpConfiguration.Id | Should -Match $edge00
I have done quite a bit of searching, but I am unable to find a way via normal PowerShell commands or Pester to check if a string ($id
)contains either string1 ($edge00
) or string2 ($edge01
)
Does anyone have any ideas, please?
As boxdog suggests, using Should
's -Match
parameter with a regular expression that employs alternation (|
) matches any of multiple substrings, just like with PowerShell's -match
operator:
$edge00 = 'bar'
$edge01 = 'foo'
# Each input must contain substring 'bar' or substring 'foo'
'food', 'rebar' | Should -Match "$edge00|$edge01' # OK
The slight caveat is that if your subexpressions come from variables, as in your case, it's generally better to use [regex]::Escape()
to ensure that they are treated as literals:"$([regex]::Escape($edge00))|$([regex]::Escape($edge01))"
.
It isn't strictly necessary here, but it's something to keep in mind for scenarios where you don't know the specific variable content in advance.
Also, you may want the matching to be more constrained to rule out false positives:
"/$([regex]::Escape($edge00))/|/$([regex]::Escape($edge01))/"
.
If you want to match entire strings, literally, use -BeIn
, which works like PowerShell's -in
operator:
# Each input must be either 'rebar' or 'food'
'food', 'rebar' | Should -BeIn rebar, food # OK
In your case, you can preprocess your inputs to extract the tokens of interest, which then allows you to use -BeIn
, without concerns about escaping or false positives; a simplified example:
$edge00 = 'FW-ASDF-EDGE-00-NIC1'
$edge01 = 'FW-ASDF-EDGE-01-NIC1'
# Extract the 3rd-from-last token from each path, which must either
# be $edge00 or $edge01
('/.../.../networkInterfaces/FW-ASDF-EDGE-00-NIC1/more/stuff',
'/.../.../networkInterfaces/FW-ASDF-EDGE-01-NIC1/more/stuff' -split '/')[-3] |
Should -BeIn $edge00, $edge01 # OK
This approach also obviates the need for separate variables, because you could instead define a single array variable - $edges = 'FW-ASDF-EDGE-00-NIC1', 'FW-ASDF-EDGE-01-NIC1'
- and pass that to -BeIn
.