Azure Powershell Positional Parameter error - azure

I'm trying to do a deployment using powershell. Both parameter and template file are stored in blob storage, but I get the error below before it even tries to download the blobs.
New-AzResourceGroupDeployment : A positional parameter cannot be found that accepts argument 'newdeployment-878059'. At C:\Temp\New-Deployment\deploy-core.ps1:86 char:1
The code I use is below
$vnetRG = "rg-vnet"
$vpnRG = "rg-vpn"
$fwRG = "rg-fw"
$btnRG = "rg-bastion"
$loc = "west europe"
New-AzResourceGroupDeployment -Name = "newdeployment-$random"-ResourceGroupName "rg-vnet" `
-TemplateParameterFile "$PSScriptRoot\core.parameters.json" -TemplateUri = $templateFileUri `
-vpnResourceGroupName $rgRG -vpnResourceGroupName $vpnRG -fwResourceGroupName $fwRG -btnResourceGroupName $btnRG
I'm trying to deploy multiple resources to various resource groups in one subscription.
Thanks in advance :)

Here my comment as answer
In your code, you have added an = character between some of the parameter names and the actual value to use for that parameter.
In PowerShell you assign a value to a parameter with a space character between the two.
Also, there are parameters used that (according to the docs) don't exist for that cmdlet, like vpnResourceGroupName, fwResourceGroupName and btnResourceGroupName. To me, they sound like variables mistakenly added as parameter with the leading $ stripped off?
For cmdlets that can potentially use a large number of parameters, I'd recommend using Splatting, to keep the code clean and easy to maintain.
Something like:
$splatParams = #{
Name = "newdeployment-$random"
ResourceGroupName = "rg-vnet"
TemplateParameterFile = "$PSScriptRoot\core.parameters.json"
TemplateUri = $templateFileUri
}
New-AzResourceGroupDeployment #splatParams

Related

Need to apply an if condition based on a check in Powershell

I am new to Powershell. I am actually getting the details of the azure data factory linked services but after get I need to use contains to check if the element exists. In python I would just check if string in a list but powershell not quite sure. Please check the code below.
$output = Get-AzDataFactoryV2LinkedService -ResourceGroupName $ResourceGroupName -DataFactoryName "xxxxxxxx" | Format-List
The output of the below is :
sample output given below
LinkedServiceName : abcdef
ResourceGroupName : ghijk
DataFactoryName : lmnopq
Properties : Microsoft.Azure.Management.DataFactory.Models.AzureDatabricksLinkedService
So now I try to do this:
if ($output.Properties -contains "Microsoft.Azure.Management.DataFactory.Models.AzureDatabricksLinkedService") {
Write-Output "test output"
}
But $output.Properties gives us the properties of that json.
I need to check if "Microsoft.Azure.Management.DataFactory.Models.AzureDatabricksLinkedService" exists in output variable and perform the required operations. Please help me on this.
The -contains operator requires a collection and an element. Here's a basic example of its proper use:
$collection = #(1,2,3,4)
$element1 = 5
$element2 = 3
if ($collection -contains $element1) {'yes'} else {'no'}
if ($collection -contains $element2) {'yes'} else {'no'}
What you've done is ask PowerShell to look in an object that isn't a collection for an element of type [string] and value equal to the name of that same object.
What you need to do is inspect this object:
$output.Properties | format-list *
Then once you figure out what needs to be present inside of it, create a new condition.
$output.Properties.something -eq 'some string value'
...assuming that your value is a string, for example.
I would recommend watching some beginner tutorials.

How to pass number of runtime parameters to variables in Azure pipeline?

I am using Azure Devops pipeline to automate azure alert creation using ARM deployment tasks. In order to automate the threshold values for the alerts I created runtime parameters inside the pipeline, which need to be replaced by a replace token task and will update the corresponding runtime parameter values to the "parameters.json" file.
Here I am facing challenge like, in order to replace the values of runtime parameters to parameters.json, first I need to convert the parameter values to variable either by defining those variables under variable section or by using a bash task separately to output the variable value. I am looking for solutions for below requirements
Is there any any method to directly update the runtime parameter values to the "parameters.json"
Can we add sub values to parameter values? For example, only need to have certain run time parameter values if the alert category is logquery type-metricmeasurement and other set of values required if the type is "count type".
If you are trying to do it with a parameters.json it is a bit inconvenient. Why ? Because you have to parse the json and then update the desired nodes in json using PS/Bash script at runtime.
I will propose another solution to do this. Use template parameter object instead of parameters.json. Just call the ARM template using PS/Bash
example creating a VM-
$a = "abc"
$b = "efg"
$c = "hij"
$d = "klm"
$e = "nop"
$paramList =
#{
"Params1" = #{ customVmName = $a ; userImageStorageAccountName = $b ; adminUsername = $c ; adminPassword = $d ; osDiskVhdUri = $e }
}
foreach ($keys in $paramList.Keys)
{
$paramvalues = $paramList.$keys
New-AzureRmResourceGroupDeployment -ResourceGroupName "deploymentRG" -TemplateFile "YourARMTemplate.json" -TemplateParameterObject $paramValues
}
Coming to part to of your question :
Overriding the values at runtime in Azure DevOps
Parameterize the script and override the values while you call the PS file.
If you are using PS task in Azure DevOps just override the param values in the argument section-
If you are a PS/Bash guy you can do the manipulation in the part of script lets say setting $a="abc" based on a condition or env and for another env a different value, mean to say the overriding of a param value can be done as a code at runtime (Just another option)

How can I get Azure container state from command line?

I wonder how I can filter by the 'State' of the container group from the command line (Get-AzContainerGroup or az container list).
In azure portal this field is reported as 'Status'.
But I can't get it from the command line, it seems this field is not provisioned.
Get-AzContainerGroup | fl
ResourceGroupName : rg-foo
Id : /subscriptions/foo/resourceGroups/foo/providers/Microsoft.ContainerInstance/containerGroups/test-01
Name : test-01
Type : Microsoft.ContainerInstance/containerGroups
Location : westeurope
Tags : {}
ProvisioningState : Succeeded
Containers : {test-01}
ImageRegistryCredentials : {}
RestartPolicy : OnFailure
IpAddress : 20.82.63.136
DnsNameLabel :
Fqdn :
Ports : {80}
OsType : Linux
Volumes : {}
State :
Events : {}
Identity :
I've tried :
Get-AzContainerGroup | Where-Object {$_.State -eq "Succeeded"}
But as field seems was reported, it didn't work.
So, the Status column/property that you see on the Azure Portal actually translates to properties.instanceView.state for an Azure Container Instance.
It seems like this property isn't populated although present in the ouput of Get-AzContainerGroup | fl *. However, when the ResourceGroupName and Name parameters are passed along, you'd see it shows up!
Digging a little deeper, this is because the Get-AzContainerGroup cmdlet invokes the Container Groups - List REST API under the hood, that does not have the instanceView property in the response.
Whereas, Get-AzContainerGroup -ResourceGroupName <Resource-Group-Name> -Name <ContainerGroup-Name> calls the Container Groups - Get REST API that returns all the extended properties as well.
So, to work around this behavior, you can run the following snippet:
# List all container groups in the current subscription
# Equivalent to [Container Groups - List]
$AllContainerGroups = Get-AzContainerGroup
# Initialize an empty array to hold all container group objects with their extended properties
$AllContainerGroupsExtended = #()
foreach($ContainerGroup in $AllContainerGroups)
{
# Gets a specific container group
# Equivalent to [Container Groups - Get]
$ContainerGroupExtended = Get-AzContainerGroup -ResourceGroupName $ContainerGroup.Id.Split('/')[4] -Name $ContainerGroup.Name
$AllContainerGroupsExtended += $ContainerGroupExtended
}
# You can now filter the result as needed
$AllContainerGroupsExtended | Where-Object {$_.InstanceViewState -eq "Stopped"}

azure powerhsell integration account partner creation identities invalid

I have a paid and free integration account setup on Azure. I have already generated a few partners and agreements using the portal with no issues. Im now looking to use some powershell scripts to help control the creation of these partners and agreements in the future.
When trying to build script to create a partner I hit this bottleneck with the business identities.
New-AzIntegrationAccountPartner -ResourceGroupName $ResourceGroupName …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Invalid business identity.
$ResourceGroupName = 'rg-test'
$IntegrationAccountName = 'inter-test'
$PartnerName = 'TestPartner'
$BusinessIdentities = #{
Qualifier = "AS2Identity"
Value = "TestIdentity"
}
New-AzIntegrationAccountPartner -ResourceGroupName $ResourceGroupName -Name $IntegrationAccountName -PartnerName $PartnerName -BusinessIdentities $BusinessIdentities
Reference: https://learn.microsoft.com/en-us/powershell/module/az.logicapp/new-azintegrationaccountpartner?view=azps-4.6.1
Is there something Im unaware when it comes to hash-tables?
Powershell Core MacOS 10.15.6
Major Minor Patch PreReleaseLabel BuildLabel
7 0 3
Update:
Adding Resolve-AzError Response.
HistoryId: 4
Message : Invalid business identity.
StackTrace : at Microsoft.Azure.Commands.LogicApp.Utilities.CmdletHelper.ConvertToBusinessIdentityList(Object businessIdentityObject)
at Microsoft.Azure.Commands.LogicApp.Cmdlets.NewAzureIntegrationAccountPartnerCommand.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__3`1.<ExecuteSynchronouslyOrAsJob>b__3_0(T c)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord()
Exception : System.Management.Automation.PSArgumentException
InvocationInfo : {New-AzIntegrationAccountPartner}
Line : New-AzIntegrationAccountPartner -ResourceGroupName $ResourceGroupName -Name $IntegrationAccountName -PartnerName $PartnerName -BusinessIdentities
$BusinessIdentities
Position : At /Users/john/Desktop/run.ps1:10 char:1
+ New-AzIntegrationAccountPartner -ResourceGroupName $ResourceGroupName …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HistoryId : 4
According to my research, when we run the command New-AzIntegrationAccountPartner, we need to define BusinessIdentities as Array. Becase the code Microsoft.Azure.Commands.LogicApp.Utilities.CmdletHelper.ConvertToBusinessIdentityList(Object businessIdentityObject) in the command New-AzIntegrationAccountPartner need users to provide Array object. Otherwise, it will throw error. For more details, please refer to here and here.
For example
$ResourceGroupName = 'testaks'
$IntegrationAccountName = 'test06'
$PartnerName = 'TestPartner'
$BusinessIdentities = #("<the Qualifier's value such as AS2Identity>","<The Value's value>")
New-AzIntegrationAccountPartner -ResourceGroupName $ResourceGroupName -Name $IntegrationAccountName -PartnerName $PartnerName -BusinessIdentities $BusinessIdentities

Get Cosmosdb Container Collection items using powershell

Team, I had created new CosmosDB account in Azure portal with a container contains list of collection items. I am able to access Container details in power shell script.
How to list collection items or show specific collection item using partition key using power shell script
Power shell Script :
Get-AzResource -ResourceType "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers" -ApiVersion "2020-03-01" -ResourceGroupName "testRG" -Name "cosmosaccount1/database1/containercollection1"
You would need to use something like a thirdparty module for this. Azure Resource Manager doesnt support that, hence you need to talk to Cosmos DB directly.
https://github.com/PlagueHO/CosmosDB
The Cosmos DB repo has a set of examples to use Powershell: https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/PowerShellRestApi
Particularly to read Items: https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/PowerShellRestApi/PowerShellScripts/ReadItem.ps1
They are all using the REST API to do REST request, in this case, it is an authenticated GET to https://{databaseaccount}.documents.azure.com/dbs/{db-id}/colls/{coll-id}/docs/{id} (where databaseaccount is your account name, db-id is the id of your database, coll-id is the id of your collection/container, and id is your document id). It is also setting the x-ms-documentdb-partitionkey header for the partition key.
Like #4c74356b41 has indicated, you can use the CosmosDB module, which is now part of the official Az module.
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
You can see the available commands with Get-Commands:
Import-Module Az
Import-Module -Name CosmosDB
Get-Command -Module CosmosDB
Get all items in a collection
In order to get all entries inside a container, we use the Get-CosmosDbDocument command:
$subscription = "SubscriptionName"
$resourceGroupName = "ResourceGroupName"
$accountName = "AzureCosmosDBAccount"
$databaseName = "DatabaseName"
$cosmosContainer = "TargetCosmosDBContainer"
Set-AzContext $subscription
$backOffPolicy = New-CosmosDbBackoffPolicy -MaxRetries 5 -Method Additive -Delay 1000
$cosmosDbContext = New-CosmosDbContext -Account $accountName -Database
$databaseName -ResourceGroup $resourceGroupName -BackoffPolicy $backOffPolicy
$documentsPerRequest = 100
$continuationToken = $null
$documents = $null
do {
$responseHeader = $null
$getCosmosDbDocumentParameters = #{
Context = $cosmosDbContext
CollectionId = $cosmosContainer
MaxItemCount = $documentsPerRequest
ResponseHeader = ([ref] $responseHeader)
}
if ($continuationToken) {
$getCosmosDbDocumentParameters.ContinuationToken = $continuationToken
}
$documents += Get-CosmosDbDocument #getCosmosDbDocumentParameters
$continuationToken = Get-CosmosDbContinuationToken -ResponseHeader $responseHeader
} while (-not [System.String]::IsNullOrEmpty($continuationToken))
Note: There is no apparent limitation on the number of documents that can be retrieved with this command, but it stands to reason that the command will have the API limitation, and this is 4 MB (as documented here). The value here ($documentsPerRequest = 100) could prove to be either too big or too small, depending on the size of each document. I usually don't use this parameter, but I've mentioned it here in case someone needs it.
List specific collection item
To get a specific entry or group of entries from a container, we use the same Get-CosmosDbDocument command, in a slightly different way:
$query = "SELECT * FROM c WHERE c.property = 'propertyValue'"
$documents = Get-CosmosDbDocument -Context $cosmosDbContext -CollectionId $cosmosContainer -Query $query -QueryEnableCrossPartition $true
Note: For brevity I haven't went to the process of getting a continuation token, but if the query will return a result that is larger than 4 MB, then we will only receive the first part of the response. To make sure this does not happen we should add "Query" and "QueryEnableCrossPartition" in the $getCosmosDbDocumentParameters dictionary.

Resources