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

Running this below and can't seem to get the collection correct to pass into the ForEach loop, even though it returns the names I want.
$RGInfo returns as expected. But when I pass it into the loop to Set-AzureRmResourceGroup, it errors as below
PS H:\> $rginfo
ResourceGroupName
-----------------
rg-crp-d365-bp-n
rg-crp-d365-dev1-n
rg-crp-d365-dev2-n
rg-crp-d365-upgrad-n
$RGInfo = Get-AzureRmResourceGroup | Where-Object {$_.ResourceGroupName -like "RG-CRP-D365*" } | Select-Object ResourceGroupName
ForEach ($RGName in $RGInfo) {
If ($RGName.Tags -eq $null) {
Set-AzureRmResourceGroup -ResourceGroupName $RGName -Tag #{BUSINESS_UNIT="CRP"; COST_CENTER="6435" }
}
}
Know why I keep getting the below? There are four RG's so the ForEach loop is functional.
Set-AzureRmResourceGroup : 'resourceGroupName' does not match expected
pattern '^[-\w._()]+$'. At line:7 char:2
+ Set-AzureRmResourceGroup -ResourceGroupName $RGName -Tag #{BUSINESS_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmResourceGroup], ValidationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetA
zureResourceGroupCmdlet Set-AzureRmResourceGroup :
'resourceGroupName' does not match expected pattern '^[-\w._()]+$'.
At line:7 char:2
+ Set-AzureRmResourceGroup -ResourceGroupName $RGName -Tag #{BUSINESS_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmResourceGroup], ValidationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetA
zureResourceGroupCmdlet Set-AzureRmResourceGroup :
'resourceGroupName' does not match expected pattern '^[-\w._()]+$'.
At line:7 char:2
+ Set-AzureRmResourceGroup -ResourceGroupName $RGName -Tag #{BUSINESS_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmResourceGroup], ValidationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetA
zureResourceGroupCmdlet Set-AzureRmResourceGroup :
'resourceGroupName' does not match expected pattern '^[-\w._()]+$'.
At line:7 char:2
+ Set-AzureRmResourceGroup -ResourceGroupName $RGName -Tag #{BUSINESS_ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmResourceGroup], ValidationException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetA
zureResourceGroupCmdlet

First you filtered the content of $RGInfo to only the Resource Group name, you cannot add tags to just the name
$RGInfo = Get-AzureRmResourceGroup | Where-Object {$_.ResourceGroupName -like "RG-CRP-D365*" } | Select-Object ResourceGroupName
Below syntax should work.
$RGInfo = Get-AzureRmResourceGroup | Where-Object {$_.ResourceGroupName -like "RG-CRP-D365*" }
ForEach ($RGName in $RGInfo)
{
If ($RGName.Tags -eq $null)
{
Set-AzureRmResourceGroup -ResourceGroupName $RGName.ResourceGroupName -Tag #{BUSINESS_UNIT="CRP"; COST_CENTER="6435" }
}
}
Hope this helps.

I had a similar issue when importing a list from a CSV file. Turns out the RG names had spaces on it 🤦‍♂️.

Related

How to add tags on specific Resourcegroups?

I need to add tags on only the ResourceGroups (which I don't know the name of) where a Keyvault is in. It is possible that there are more than one Keyvaults in several Resourcegroups.
This is how I tried:
Set-AzContext -Subscription $subscriptionID
#Add Currentdate on resourcegroup of Keyvault
$CurrentDate = ((Get-Date).ToString('dd-MM-yyyy'))
$Tags = #{'Date' = $Currentdate}
$Resources = (Get-AzKeyVault).ResourceGroupName
Foreach ($Resource in $Resources){
$ResourcegroupName = (Get-AzKeyVault).ResourceGroupName
$ResourcegroupId = (Get-AzResourceGroup -Name $ResourcegroupName).ResourceId
New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
}
The commands work separately but in this context it gives multiple errors (below error 3 times). Getting the ResourceId gives by what I can see the main error:
Get-AzResourceGroup : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified method is not supported.
At line:11 char:47
+ ... sourcegroupId = (Get-AzResourceGroup -Name $ResourcegroupName).Resour ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-AzResourceGroup], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceGroupCmdlet
New-AzTag : Cannot validate argument on parameter 'ResourceId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:12 char:27
+ New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-AzTag], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Tags.Tag.NewAzureTagCommand
Thanks a lot for your help!
I understand that you need to add tags on only the ResourceGroups where a Keyvault is in.
I modified a bit your code:
Set-AzContext -Subscription $subscriptionID
#Add Currentdate on resourcegroup of Keyvault
$CurrentDate = ((Get-Date).ToString('dd-MM-yyyy'))
$Tags = #{'Date' = $Currentdate}
$Resources = (Get-AzKeyVault).ResourceGroupName
Foreach ($Resource in $Resources){
$ResourcegroupId = (Get-AzResourceGroup -Name $Resource).ResourceId
New-AzTag -ResourceId $ResourcegroupId -Tag $Tags
}

GetEnumerator error whilst running my script

I am trying to extract and export Azure Webapp settings using the below script
$allWebApps = Get-AzureRmWebApp
$resourceGroups = $allWebApps | Select-Object 'ResourceGroup' -Unique
foreach($r in $resourceGroups)
{
$rgName = $r.ResourceGroup
$webApps = Get-AzureRmWebApp -ResourceGroupName $rgName
foreach($w in $webApps)
{
$webAppName = $w.Name
Write-Host Processing Webapp : $webAppName
$webApp = Get-AzureRmWebApp -ResourceGroupName $rgName -Name $webAppName
$appSettings = $webApps.SiteConfig.AppSettings
# Extract AppSettings to CSV
$appSettings.GetEnumerator() |
Sort-Object -Property Name -Descending |
Select-Object -Property #{n='Key';e={$_.Name}},Value |
Export-Csv -Path "C:\Cloud\$webAppName.csv" -NoTypeInformation -Append
}
}
but I keep getting the below error:
You cannot call a method on a null-valued expression.
At C:\Cloud\ExportsWebApp_config.ps1:17 char:9
+ $appSettings.GetEnumerator() |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
can someone please assist?
$appSettings = $webApps.SiteConfig.AppSettings
I think this line should be changed, otherwise you're trying to get the properties of the entire array of web apps.
$appSettings = $webApp.SiteConfig.AppSettings

Enable/Disable availability tests in Azure on Schedule

I'm wondering if there is an easy way to run scheduled automation commands in Azure.
I managed to write Enable/Disable command for availability tests both in
Azure CLI:
az resource update --set properties.enabled=true --name 'someName' --resource-type 'Microsoft.Insights/webtests' --resource-group 'soemResourceGroup'
and
Powershell:
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
problem is that I'm not sure to run them outside of Comamnd line and on schedule. I've read that I could use Automation account to use powershell scripts but that seems a nightmare since I got tons of issues with authentication (not sure why).
Is that an only way ?
EDIT:
I post the errror I was/am getting below.
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Set-AzureRmResource : Cannot validate argument on parameter 'Sku'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At line:37 char:29
+ $availabilityTest | Set-AzureRmResource -Force;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Microsoft.Azure...dels.PSResource:PSObject) [Set-AzureRmResource],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationError,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.SetAzureResourceCmdlet
Regards.
You could follow the steps as below to use the azure runbook in automation to do that.
1.Navigate to your automation account -> Runbooks -> Create a runbook -> create a Powershell runbook.
2.In the runbook, add the script to login, your complete script should be like below. (Before running the runbook, make sure you have imported the AzureRM.Resources and AzureRM.Profile powershell module in your automation account -> Modules, if not, in the Modules -> Browse Gallery, search for the modules and import them.)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
#Get All webTests
$resourceGroupnames = "someGroupName1", "someGroupName2";
$enableTests = "True";
ForEach ($resourceGroupname in $resourceGroupnames) {
$resourceGroupname
$allAvailabilityTestsIds = Get-AzureRmResource -ResourceGroupName $resourceGroupname `
| Where-Object -Property ResourceType -EQ "microsoft.insights/webtests" `
| Select-Object -ExpandProperty ResourceId;
ForEach ($availabilityTestId in $allAvailabilityTestsIds) {
$availabilityTest = Get-AzureRmResource -ResourceId $availabilityTestId;
$availabilityTest.Properties.Enabled = $enableTests;
$availabilityTest | Set-AzureRmResource -Force;
}
}
3.After running the script successfully, follow this link Scheduling a runbook in Azure Automation to add a schedule to your runbook.

Why isn't VScode pwsh terminal able to see my azure resource groups?

I'm trying to tag all my running VMs from azure with tags from a CSV file but my PowerShell script is failing when being run from VSCode PowerShell core terminal.
I double-checked and I have set the correct active subscription (we have multiple tenants and subscriptions), but the output says that it can't find my resource groups (they are there for sure).
Enable-AzureRmAlias
$csv = import-csv "C:\Users\popes\Desktop\Jedox\Powershell scripts\Tagging\Tagging.csv"
$csv | ForEach-Object {
# Retrieve existing tags
$tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Microsoft.Compute/virtualMachines" -Name $_.VM).Tags
# Define new value pairs from CSV
$newTags = #{
company = $_.Company
dns = $_.DNS
type = $_.Type
CN = $_.CN
}
# Add new tags to existing set (overwrite conflicting tag names)
foreach($CN in $newTags.Keys){
$tags[$_] = $newTags[$_]
}
# Update resource with new tag set
Set-AzResource -ResourceGroupName $_.RG -Name $_.VM -Tag $tags -ResourceType "Microsoft.Compute/virtualMachines"
}
The output:
Get-AzResource : Resource group 'machine774_rg' could not be found.
At line:3 char:14
+ ... $tags = (Get-AzResource -ResourceGroupName $_.RG -ResourceType "Mi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzResource], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.GetAzureResourceCmdlet
Cannot index into a null array.
At line:15 char:9
+ $tags[$_] = $newTags[$_]
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Try to use Clear-AzContext, then login with specific tenant and subscription, Connect-AzAccount -Tenant "xxxx-xxxx-xxxx-xxxx" -SubscriptionId "yyyy-yyyy-yyyy-yyyy".

Powershell jobs and Set-AzureRmRouteTable

I keep getting this error when I use this cmdlet in my script block
Cannot parse the request.
StatusCode: 400
ReasonPhrase: Bad Request
OperationID : '2410b534-3ab9-4c82-b0fa-233e5a36e795'
+ CategoryInfo : CloseError: (:) [Set-AzureRmRouteTable], NetworkCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Network.SetAzureRouteTableCommand
+ PSComputerName : localhost
Makes no sense to me. Everytime I search this error, it references Network related cmdlets.
$addConfigBlock = {
Param(
$udr,
$routeTableName,
$routeTableRG
)
$routeTable = Get-AzureRmRouteTable -ResourceGroupName $routeTableRG -Name $routeTableName
try{
Add-AzureRmRouteConfig -RouteTable $routeTable `
-Name $udr.Name `
-AddressPrefix $udr.properties.addressPrefix `
-NextHopType $udr.properties.nextHopType | `
Set-AzureRmRouteTable | Out-Null
}
catch {
$ErrorMessage = $_.Exception.Message
Write-Output "$ErrorMessage"
}
}
foreach( $routeTable in $routeTablesToUpdate){
Write-Output "Updating routes in route table : $($routeTable.Name) ..."
ForEach($udr in $udrGov){
Start-Job -ScriptBlock $addConfigBlock -ArgumentList $udr, $routeTable.Name, $routeTable.ResourceGroupName
}
}
Some of the new configurations are added to my route table, but some error out with that error.. Hm..
New error -
A retryable error occurred.
StatusCode: 429
ReasonPhrase:
OperationID : '927995e6-da07-4f99-bbf3-6dd59e7c3183'
+ CategoryInfo : CloseError: (:) [Set-AzureRmRouteTable], NetworkCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Network.SetAzureRouteTableCommand
+ PSComputerName : localhost
I have reproduced your issue via an existing route name, before I run the command, I have a route called joyroute1 in the route table.
My test command:
$routeTable = Get-AzureRmRouteTable -ResourceGroupName joywebapp -Name joyudr
Add-AzureRmRouteConfig -RouteTable $routeTable `
-Name joyroute1 `
-AddressPrefix 10.1.0.0/18 `
-NextHopType VirtualNetworkGateway | `
Set-AzureRmRouteTable -Debug
Debug result:
So I think that your script uses conflict names of the routes, when it using some different names, it works, this explains why some of them work, you could check it.

Resources