问题描述:

I'm trying to search for a ResourceGroup with the name containing "XYZ" and handle with Try{} Catch{} depending on its existence. I'm sure it should be simple, but I cannot fathom why it doesn't like this:

Get-AzureRmResourceGroup -Name "[MK3]" #No error as it exists

Get-AzureRmResourceGroup -Name "[BLAH]" #Errors as it doesn't exist

The error returned is:

Get-AzureRMResourceGroup : 'resourceGroupName' does not match expected pattern '^[-\w\._\(\)]+$'.

At line:1 char:1

+ Get-AzureRMResourceGroup -Name [MK3]

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : CloseError: (:) [Get-AzureRmResourceGroup], ValidationException

+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceGroupCmdlet

This works:

Get-AzureRmResourceGroup | Where-Object{$_.ResourceGroupName -like "*MK3*"}

But this method requires a bunch more 'if' statements that I prefer to avoid.

To me the error suggest the cmdlet handles wildcards, but I can't seem to get the syntax right.

Any suggestions, greatly appreciated.

网友答案:

The command “Get-AzureRmResourceGroup -Name” should specifies the name of the resource group to get, but wildcard characters are not permitted.

But we can use function to list the resource name:

PS C:\windows\system32> function test () {param ($name ) ;Get-AzureRmResourceGroup | Where-Object{$_.ResourceGroupName -like "$name"} }

So we can use test -name “test*” to instead of Get-AzureRmResourceGroup: More information about Get-AzureRmResourceGroup, please refer to the link below: https://msdn.microsoft.com/en-us/library/mt759838.aspx

If you still have questions, welcome to post back here. Thanks.
Best Regards,

网友答案:

Thank you @Jason Ye. Using your guidance, I came up with this little function:

Function Find-ResourceGroupName
{
    Param
    (
        [Parameter(Position=0)]
        [string]$SearchTerm
    )

    $ResourceGroupName = (Get-AzureRmResourceGroup | Where-Object {$_.ResourceGroupName -Match "\b$SearchTerm"}).ResourceGroupName
    If($ResourceGroupName)
    {
        Return $ResourceGroupName
    }
    else
    {
        Throw "Resource group matching search term not found ($SearchTerm)."
    }
}

Try
{
    Find-ResourceGroupName "mk3"
}
Catch
{
   Write-Error $Error[0]
}

Probably more complex than an if statement and I'm sure there's a better way, but it works nicely in my script.

Update1:

Scrub above. Using Find-AzureRMResource does the job for me and it's builtin. For Example:

Find-AzureRmResource -ResourceGroupNameContains $ProjectCode | Where-Object {$_.ResourceType -like "*$ResourceType"}

$ProjectCode is just a 5 character reference found in our Resource Group Names.

相关阅读:
Top