Using Service Bus Queue InputObject Parameter on Powershell - azure

I have a Azure Service Bus Namespace which has hundreds of queues and I need to Set the MaximumDeliveryCount to 1 instead of a default value of 10. Doing it manually on portal will obviously take time. So I want to do it through PowerShell Script.
Not sure what should be the -InputObject Parameter. The Microsoft article Set-AzServiceBusQueue says that the InputObject Type is of PSQueueAttributes given here PSQueueAttributes Class
I tried entering 'MaxDeliveryCount' attribute but receiving this error:
Set-AzServiceBusQueue : Cannot bind parameter 'InputObject'. Cannot convert the "MaxDeliveryCount" value of type "System.String" to type
"Microsoft.Azure.Commands.ServiceBus.Models.PSQueueAttributes".
At line:7 char:121
+ ... $Servicebus_namespace -Name $_ -InputObject MaxDeliveryCount -WhatIf
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-AzServiceBusQueue], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.Azure.Commands.ServiceBus.Commands.Queue.SetAzureRmServiceBusQueue
Here is the code:
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace).Name
$Servicebus_queue
$Servicebus_queue.foreach{
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace)
$Servicebus_queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject MaxDeliveryCount
}
I've researched everywhere but could not find any solution. Also the above links route to AzureRM module for Set-AzServiceBusQueue command.
Appreciate if anyone can help.

As per my comment, you need to pass a queue object (i.e. a PSQueueAttributes instance) into Set-AzServiceBusQueue, but you've also got something slightly screwy going on with your variable assignments and your foreach.
The sample below should hopefully help straighten things out...
# get a queue (or an array of queues). remove the ().Name as this just extracts
# their names and we really want the whole queue object. also, pluralise the
# variable name so it doesn't collide with our loop variables
$Servicebus_queues = Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace
$Servicebus_queues.foreach{
# get a reference to the current ppieline variable
# see https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-6#_
$Servicebus_queue = $_
$Servicebus_queue.MaxDeliveryCount = 1
# -InputObject needs to be a queue (i.e. a PSQueueAttributes instance)
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject $Servicebus_queue
}

According to my research, If you want to use the parameter InputObject, you can must provide PSQueueAttributes as its value.
For example :
$Servicebus_queue = (Get-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace)
$Servicebus_queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroupName $Resourcegroup_name -Namespace $Servicebus_namespace -Name $_ -InputObject $Servicebus_queue
For more details, please refer to the document.
Update
If you want to update Service Bus Queue with PowerShell, please refer to the following script
Connect-AzAccount
$ResourceGroupName=" "
$Namespace=" "
$queues = Get-AzServiceBusQueue -ResourceGroupName $ResourceGroupName -Namespace $Namespace
foreach($queue in $queues){
$queue.MaxDeliveryCount = 1
Set-AzServiceBusQueue -ResourceGroup $ResourceGroupName -NamespaceName $Namespace -QueueName $queue.Name -QueueObj $queue
}

Related

Parse Excel variables into powershell

I am trying to create a powershell that will grab the varibles from an excel sheet and then add them to the powersehll command.
in the excel sheet i have 3 columns i am interested in the data from (Name , resourcegroup, location)
And then for each line with this i want it to parse into into the varible field for the powershell
I have created the powershell to do what i need but it would be better if it could loop through and pull this as I am just running the command again with different machine info manually added from the excel.
With #Theo Help
I am working with this version of the script now
Import-Csv -Path 'c:\scripts\vmtest.csv' | ForEach-Object {
# combine the VMName with suffix '-Snapshot'
$snapshotName = $vm.name + "-Snapshot"
$SnapshotStorage = "Azure-Snapshots"
$vm = Get-AzVM -ResourceGroupName $_.ResourceGroup -Name $_.Name
# using splatting for better readability
$configParams = #{
SourceUri = $vm.StorageProfile.OsDisk.ManagedDisk.Id
Location = $_.location
CreateOption = 'copy'
}
$snapshot = New-AzSnapshotConfig #configParams
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotname -ResourceGroupName $snapshotstorage
}
If as you have commented, you now have the data stored in a CSV file that might look something like this:
Name,ResourceGroup,Location
PRD-ITM001,SJAVIRTUALMACHINES,uksouth
TST-GRSSQL001,SJAVIRTUALMACHINES,uksouth
it has become very simple to import that data and loop through the records like below:
Import-Csv -Path 'c:\scripts\vmtest.csv' | ForEach-Object {
# combine the VMName with suffix '-Snapshot'
$snapshotName = '{0}-Snapshot' -f $_.Name
$SnapshotStorage = "Azure-Snapshots"
$vm = Get-AzVM -ResourceGroupName $_.ResourceGroup -Name $_.Name
# using splatting for better readability
$configParams = #{
SourceUri = $vm.StorageProfile.OsDisk.ManagedDisk.Id
Location = $_.Location
CreateOption = 'copy'
}
$snapshot = New-AzSnapshotConfig #configParams
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $_.ResourceGroup
}
Note that the above code assumes your CSV uses the (default) comma as delimiter character. If in your case this is some other character, append parameter -Delimiter followed by the character the csv uses.
Inside a ForEach-Object {..} loop, the $_ automatic variable references the current record from the csv
I used Splatting for better readability of the code. This helps on cmdlets that take a long list of parameters and eliminates the use of the backtick.
Based on the above shared requirement, we understood that you want to pull the values of ResourceGroupName, VMName from the excel sheet & also you want to use those values in the script further.
Using PSExcel Module, We have written the below PowerShell Script which will pull the ResourceGroupName, VMName from excel & it will run Get-AzVM Cmdlet.
Before running the below PowerShell script , run the below cmdlet Save-Azcontext cmdlet it will saves the current authentication information for use in other PowerShell sessions.
Connect-AzAccount
Save-AzContext -Path C:\test.json
Here is the PowerShell script:
$currentDir = "C:\Program Files\WindowsPowerShell\Modules" ##pass the path of the PSexcel Module
Import-Module $currentDir"\PSExcel"
Import-AzContext -Path C:\test.json ##passing the azcontext file path which was saved earlier
$ExcelFile = "Give here the path of the current folder where scripts are stored"
$objExcel = New-Excel -Path $ExcelFile
$WorkBook = $objExcel|Get-Workbook
ForEach($Worksheet in #($Workbook.Worksheets)){
$totalNoOfRecords = $Worksheet.Dimension.Rows
$totalNoOfItems = $totalNoOfRecords-1
# Declare the starting positions first row and column names
$rowNo,$colResourceGroupName = 1,1
$rowNo,$colVMName = 1,2
if ($totalNoOfRecords -gt 1){
#Loop to get values from excel file
for($i=1;$i -le ($totalNoOfRecords-1);$i++){
$ResourceGroupName=$Worksheet.Cells.Item($rowNo+$i,$colResourceGroupName).Value
$VMName=$Worksheet.Cells.Item($rowNo+$i,$colVMName).Value
Get-AzVM -ResourceGroupName $ResourceGroupName -Name $VMName |select -Property Name,ResourceGroupName,Location
}
}
}
Here is the sample output for reference:
For more information ,you refer this blog post on How to Read excel file using PSExcel Module in PowerShell.

use Invoke-AzVMRunCommand -Params

I am trying to use the command like so:
a = 345
name = "myVM"
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = "a"; "test" = "name"}
the script in the file isn't really important I am just trying to use params inside of it with values of params from the outside. If I put "b" = 345 it works but with the outside param (a), it doesn't so I wanted to know how to do it.
it does execute the script but ignores the commands using these params.
for reference the script is something like this:
New-Item -Path "." -Name "index.html" -ItemType "file" -Value $b
New-Item -Path "." -Name $test -ItemType "file" -Value "3333333"
We use Invoke-AzVMRunCommand to Invoke a run command on the VM. And the -Parameter is used to run the command parameter.
The the type for -Parameter is Hashtable, which maps keys to values. Any non-null object can be used as a key or as a value.
Invoke command is more like a batch script, so when we want to pass a pre-defined variable we have to use the $ symbol without any double quotes (""). So you can solve your problem by following the code snippet below.
#Example
a = 345
name = "myVM"
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = $a; "test" = $name}
Read this Invoke-AzVMRunCommand document and about_Hash_Tables document for more information.
Invoke-AzVMRunCommand -ResourceGroupName $RGName -Name $VMName -CommandId 'RunPowerShellScript' -ScriptPath $FileName -Parameter #{"b" = $a; "test" = $name}
It don't work. The same problem.
I have the script which create VM in azure:
$password = ConvertTo-SecureString -String "Qwerty123456" -AsPlainText
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $password
$x = Get-Random 10000 -Minimum 10
$location = "East US"
$rgname = "testVM"+$x
$VMName = "vm1"
# Create Resource group
New-AzResourceGroup -name $rgname -Location $location
# Create VM, vnet, publicIP, port 3389
New-AzVM -ResourceGroupName $rgname `
-Location $location `
-Name "verdyshtest" `
-VirtualNetworkName "virtnet" `
-SubnetName 'verdyshnetwork' `
-PublicIpAddressName "verdyshpublicIP" `
-Image Win2019Datacenter `
-OpenPorts 3389 `
-Credential $cred
# Script only running after deploy
Invoke-AzVMRunCommand -ResourceGroupName $rgname -VMName $VMName -CommandId RunPowerShellScript -ScriptPath '.\2 Install app on VM.ps1'
In last count it can't to execute 'invoke-azvmruncommand', because of variable in parameters.
But in New-AzVM cmdlet variables works well.
Had a error:
error

How to output Subscription name with Get-AzVM

I am currently trying to output a list of VMs that are not compliant with a policy, all is working except I cant figure out how to output the subscription the VM lives in, since its not a property of Get-AzVm. If someone can please help me out, I am embarrassed I cant figure it out since it seems pretty simple. The current output will use the last subscription context for all the VMs, even though I have multiple subscriptions. Thanks a lot!
$vmsNotBackedUp = #()
$vms_results = #()
$subscriptions = Get-AzSubscription
#set policy definition
$poldef = '013e242c-8828-4970-87b3-ab247555486d'
#Get VMs resource ID that are not backed up from Azure Policy, store in $resourceIDs variable
foreach ($sub in $subscriptions) {
Set-AzContext -Subscription $sub.Id
$resourceIDs =(Get-AzPolicyState -Filter "PolicyDefinitionName eq '$poldef' and ComplianceState eq 'NonCompliant'").ResourceId
$vmsNotBackedUp += Get-AzVM | Where-Object{$_.Id -in $resourceIDs}
$currentContext = $sub.Name
$currentContext
}
Write-Output("The Following VMs were not able to be backed up, may need investigation")
#$vmsNotBackedUp|Select-Object -Property Name,ResourceGroupName,Location
foreach ($vm in $vmsNotBackedUp) {
$output_data = [PSCustomObject]#{
vmName = $vm.Name
ResourceGroup = $vm.ResourceGroupName
vmLocation = $vm.Location
vmOS = $vm.StorageProfile.OsDisk.OsType
vmSub = $currentContext
}
$vms_results += $output_data
}
Since you already have the subscription ID in $sub.Id, you could add this as a property to the VMs you enumerate in your script. Something like this:
$vmsNotBackedUp += Get-AzVM |
Where-Object{$_.Id -in $resourceIDs} |
Add-Member -MemberType NoteProperty -Name 'Subscription' -Value $sub.id -PassThru

Azure ARM template script error when creating certificate for apex domain

Really scratching my head on this one, I keep getting the error below:
New-AzureRmResourceGroupDeployment : A parameter cannot be found that matches parameter name 'SubjectName'.
At azure_cli_-_create_cert.ps1:12 char:80
for the Azure ARM template script below:
$subscription = ""
$resourceGroupName = ""
$appServicePlanName = ""
$subjectName = ""
Set-AzureRmContext -SubscriptionId $subscription
$appServicePlan = Get-AzureRmResource `
| Where-Object {$_.ResourceGroupName -eq $resourceGroupName} `
| Where-Object {$_.Name -eq $appServicePlanName}
New-AzureRMResourceGroupDeployment -ResourceGroupName $resourceGroupName -SubjectName $subjectName -AppServicePlanName $appServicePlanName -Location $appServicePlan.Location -TemplateFile "CreateHttpFreeCert.json"
Does anyone know why this is?
I am running the script in a windows powershell script (i.e. .ps1 script).
It seems like you need to supply the parameters for your template in as a JSON file using -TemplateParameterFile or -TemplateParameterObject
https://learn.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermresourcegroupdeployment?view=azurermps-6.13.0#example-1--use-a-custom-template-and-parameter-file-to-create-a-deployment

How to set value of -DefaultProfile (of type IAzureContextContainer) in New-AzSqlSyncMember

I am trying to create a powershell script to create azure data sync between 2 azure SQL databases.
My member database is on another subscription.
I need to set -DefaultProfile which is of type on 'New-AzSqlSyncMember' command.
I am not aware of the syntax for setting this parameter.
My current script without -DefaultProfile looks like below:
New-AzSqlSyncMember -ResourceGroupName $resourceGroupName `
-ServerName $serverName `
-DatabaseName $databaseName `
-SyncGroupName $syncGroupName `
-Name $syncMemberName `
-MemberDatabaseType $memberDatabaseType `
-SyncDirection $syncDirection
I want to set the value of the subscription field using powershell like in the image below using powershell:
Possible cross post from https://social.msdn.microsoft.com/Forums/en-US/4ad3dd3e-314a-4442-957f-da77c17ef85b/how-to-set-value-of-defaultprofile-of-type-iazurecontextcontainer-in-newazsqlsyncmember?forum=azurescripting&prof=required
You want to call Connect-AzAccount with the credentials for the account you want to use in the -DefaultProfile parameter and store that in a variable. You can use that variable to set the parameter:
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
New-AzSqlSyncMember <params> -DefaultContext $DefaultProfile
If this throws a type error that it can't convert from a PSAzureContext to a IAzureContextContainer there is an explicit converter available.
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
$Converter = New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.AzureContextConverter
$Container = $converter.ConvertFrom($DefaultProfile, [Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer], $null, $true)
New-AzSqlSyncMember <params> -DefaultContext $Container

Resources