Create 2 publicIPs and assign to nics - azure

I am trying to create 2 public ips and then assign one each to nics
for($i=1; $i -lt 3; $i++)
{
New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
New-AzNetworkInterface -Name "nic$i" -ResourceGroupName $resourcegroup.ResourceGroupName -Location $location -SubnetId $vnet.subnets[0].Id -PublicIpAddressId "publicIP$i.Id" -NetworkSecurityGroupId $nsg.Id
}
I want to assign the output of new-azPublicIpAddress to a variable and then use that variable's id to assign to -pulicIpAddressId.
like this $pip$i = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic but this does not work

You cannot set a variable with a '$' inside it.
The following is a correct sample.
$pip = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
Considering your requirement, I suggest you use an array:
$pipArr = New-Object 'Object[]' 2;
$nicArr = New-Object 'Object[]' 2;
for($i=0; $i -lt 2; $i++)
{
$pipArr[$i] = New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic
$nicArr[$i] = New-AzNetworkInterface -Name "nic$i" -ResourceGroupName $resourcegroup.ResourceGroupName -Location $location -SubnetId $vnet.subnets[0].Id -PublicIpAddressId $pipArr[$i].Id -NetworkSecurityGroupId $nsg.Id
}
In this way, you can get your first public IP with "$pipArr[0]". As it is an array, you can use index with it.

As Jack requested, here's another way of doing the same is the following:
Set-Variable "pip$i" -Value (New-AzPublicIpAddress -Name "publicIP$i" -ResourceGroupName $resourceGroup.ResourceGroupName -Location $location -AllocationMethod Dynamic)
then you can use Get-Variable to get data from the variable:
Get-Variable "pip$i" | Select -ExpandProperty Value
If you just want to have $ inside the variable you can do this:
${pip$i} = something
this will instanciate new variable with the name pip$i, and you could retrieve it similarly as well:
Do-something -Input ${pip$i}

Related

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

Azure-Powershell Script error (ip address increment )

I hope you all doing well
can you please help me to solve this problem?
$ipnumber = 3
$RgName = "test"
$Location = "test"
for ($i = 0; $i -lt $ipnumber; $i++) {
$res1 = -join ((1..10) | ForEach-Object { get-random -minimum 97 -maximum 122 | ForEach-Object { [char]$_ } })
$res2 = -join ((1..10) | ForEach-Object { get-random -minimum 97 -maximum 122 | ForEach-Object { [char]$_ } })
$PublicIP = '$PublicIP'
$IpConfigName = '$IpConfigName'
$IpConfig = '$IpConfig'
$ip = '10.0.0.'
$x = 25
$PublicIP = $PublicIP + $i
$IpConfigName = $IpConfigName + $i
$IpConfig = $IpConfig + $i
$x = 25 + $i
$ip = $ip + $x
#####################################
# Create a public IP address
$PublicIP = New-AzPublicIpAddress `
-Name "$res1" `
-ResourceGroupName $RgName `
-Location $Location `
-AllocationMethod dynamic
#Create an IP configuration with a dynamic private IP address and assign the public IP address to it
$IpConfigName = "$res2"
$IpConfig = New-AzNetworkInterfaceIpConfig `
-Name $IpConfigName `
-Subnet $Subnet `
-PrivateIpAddress $ip `
-PublicIpAddress $PublicIP
}
$rand6 = -join ((1..10) | ForEach-Object { get-random -minimum 97 -maximum 122 | ForEach-Object { [char]$_ } })
$NIC = New-AzNetworkInterface `
-Name $rand6 `
-ResourceGroupName $RgName `
-Location $Location `
-NetworkSecurityGroupId $NSG.Id `
-IpConfiguration $IpConfig0, $IpConfig1, $IpConfig2
Error1 :
enter image description here
Error2 :
New-AzNetworkInterface: C:\Users\Marouane\Desktop\testpowershell\test2.ps1:95:22
Line |
95 | -IpConfiguration $IpConfig, $IpConfig0, $IpConfig1
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Cannot bind parameter 'IpConfiguration'. Cannot convert the "$IpConfig1" value of type "System.String" to type
| "Microsoft.Azure.Commands.Network.Models.PSNetworkInterfaceIPConfiguration".
I want to increment the IP by 1
Ex : 10.0.0.25 next 10.0.0.26 next 10.0.0.27
but it says that you can't put in 'IpConfiguration' String ips
So what should i do ?
please help me!!
Thank you
I think Mainich you are trying do the array operation.
If I understand correctly, you are trying to create to create an array of the below variable :
$PublicIP = $PublicIP + $i
$IpConfigName = $IpConfigName + $i
$IpConfig = $IpConfig + $i
For instance,
IpConfig1,Ipconfig2,Ipconfig3 - and store the value accordingly.
Unfortunately, the implementation is slightly wrong
Please note : I have detailed the operation only for the $ipconfig variable. You can extend the same to other variables like $IpConfigName,$PublicIP
What Exactly is Happening
For all the iteration, $IpConfig gets updated & the variables you intended IpConfig1,Ipconfig2,Ipconfig3 are not created through the above logic.
You are initializing the variable ipConfig as a string
Overwriting the value of the variable ipconfig with the string value
$ipconfig1 (for the first iteration)
Overwriting the string value of the variable ipconfig with object.
AzNetworkInterfaceIpConfig
End of the iteration 1,
$ipconfig is with the value AzNetworkInterfaceIpConfig
ipconfig1 is non existant.
Suggestion :
The below creates an empty array with a fixed number - in your case 3 as $ipnumber = 3
$ipconfig = #() * $ipnumber
$ipconfig.append(New-AzNetworkInterfaceIpConfig `
-Name <>`
-Subnet<>`
-PrivateIpAddress <> `
-PublicIpAddress <>)
( or )
$ipconfig[0] = New-AzNetworkInterfaceIpConfig `
-Name <>`
-Subnet<>`
-PrivateIpAddress <> `
-PublicIpAddress <>
Now you can access the values through ipconfig[0], ipconfig[1],ipconfig[2]
Or you can pass the $ipconfig directly - as the parameter Ip configuration accepts the array value
-IpConfiguration <PSNetworkInterfaceIPConfiguration[]>
https://learn.microsoft.com/en-us/powershell/module/az.network/new-aznetworkinterface?view=azps-5.0.0
Suggestion 2:
if you would prefer creating the variable on the fly like ipconfig1,ipconfig2,ipconfig3, then you could do the below :
New-Variable -Name "Ipconfig$i" -Value <>
New-Variable -Name "Ipconfig$i" -Value <>
Get-Variable -Name "Ipconfig$i" -ValueOnly

Validate Azure Resource Group Exist or not

I am trying to write to a powershell script to validate the Resource Group is exist or not.
Conditions-
Check the resource group (myrg) is already exist in azure subscription.
If "condition 1" is FALSE then Create a Resource Group (myrg) Else append 2 digits to the Resource Group name. e.g. (myrg01)
Check the (myrg01)resource group exist in azure subscription.
If "condition 3" is FALSE then Create a Resource Group (myrg01) Else increment the last digit by one for Resource Group name. e.g. (myrg02)
Check the (myrg02) resource group exist in azure subscription.
If "condition 5" is FALSE then Create a Resource Group (myrg02) Else increment the last digit by one for Resource Group name. e.g. (myrg03)
and so on.........
Below is the code which i have written so far and unable to create a desired loop.
$rgname= "myrg"
Get-AzResourceGroup -Name $rgname -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notPresent){
Write-Host "ResourceGroup doesn't exist, Creating resource group"
$createRG= New-AzResourceGroup -Name $rgname -Location $region -Tag $tag
Write-Host $rgname
}
else{
$countcontent = $countcontent + 1
$counter = [int]$countcontent
++$counter
$countString = "{0:d2}" -f ($counter)
Write-Host "ResourceGroup $rgname already exist, Generating a new name for Resource Group"
$rgname= $rgname + $countString
Get-AzResourceGroup -Name $rgname -ErrorVariable notPresent -ErrorAction SilentlyContinue
if ($notpresent){
$createRG= New-AzResourceGroup -Name $rgname -Location $region -Tag $tag
Write-Host $rgname
Clear-Variable countcontent
Clear-Variable counter
Clear-Variable countString
}
}
Got a workaround
$rg="myrg"
$Subscriptions = Get-AzSubscription
$Rglist=#()
foreach ($Subscription in $Subscriptions){
$Rglist +=(Get-AzResourceGroup).ResourceGroupName
}
$rgfinal=$rg
$i=1
while($rgfinal -in $Rglist){
$rgfinal=$rg +"0" + $i++
}
Write-Output $rgfinal
Set-AzContext -Subscription "Subscription Name"
$createrg= New-AzResourceGroup -Name $rgfinal -Location "location"

AzCosmosDBSqlContainer : "Object reference not set to an instance of an object."

I am using AzCosmosDBSqlContainer to check details of a CosmosDB (SQL api) container in PowerShell; I am getting this error
Object reference not set to an instance of an object
However Get-AzCosmosDBAccount and Get-AzCosmosDBSqlDatabase commands are working fine.
Can someone help me with this?
Command used:
$ResourceGroup="MyResourceGroup"
$CDBAccountName="mycosmosaccount"
$dbname="myDatabase"
$containername="MyContainer"
$cosmosaccount=Get-AzCosmosDBAccount -ResourceGroupName $ResourceGroup -Name $CDBAccountName
$cosmosdbname=Get-AzCosmosDBSqlDatabase -AccountName $cosmosaccount.Name -ResourceGroupName $ResourceGroup -Name $dbname
Get-AzCosmosDBSqlContainer -ResourceGroupName $ResourceGroup -AccountName $cosmosaccount.Name -DatabaseName $cosmosdbname.Name -Name $containername
I found a workaround after getting an update from Microsoft team.
https://github.com/Azure/azure-powershell/issues/11381
This issue is going to be fixed in upcoming version of Az.CosmosDB 0.1.4
Workaround:
Replace "my***Name" with your own values
$resourceGroupName = "myResourceGroupName"
$accountName = "myAccountName"
$databaseName = "mYDatabaseName"
$containerName = "myContainerName"
$apiVersion = "2020-03-01"
$databaseResourceName = $accountName + "/" + $databaseName
$containerResourceName = $databaseResourceName + "/" + $containerName
$containerResourceType = "Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers"
Write-Host "List containers in the database"
Get-AzResource -ResourceType $containerResourceType -ApiVersion $apiVersion
-ResourceGroupName $resourceGroupName -Name $databaseResourceName
Write-Host "Show specified container"
Get-AzResource -ResourceType $containerResourceType -ApiVersion $apiVersion
-ResourceGroupName $resourceGroupName -Name $containerResourceName

What is the equivalent script in powershell for image-copy-extension extension from Azure CLI

I need to create a VM in locationA from Image ImageB which is in locationB using powershell. Since I'm not able to do it I'm trying to create a copy of ImageB into locationA, so that it will easy for me to create the VM.
I have searched for scripts to copy the images and got many results. I found one particular link which has simple script to copy images. But it is AzureCLI cmdlets. I need powershell scripts to do the job as the tool I'm using understands only powershell scripts.
I have searched for an equivalent powershell script but couldn't find any.Can anyone help me here.
Here is a script to copy the image. You could create a snapshot and copy it to anther region, then create the image.
Create a snapshot:
<# -- Create a snapshot of the OS (and optionally data disks) from the generalized VM -- #>
$vm = Get-AzureRmVM -ResourceGroupName $resourceGroupName -Name $vmName
$disk = Get-AzureRmDisk -ResourceGroupName $resourceGroupName -DiskName $vm.StorageProfile.OsDisk.Name
$snapshot = New-AzureRmSnapshotConfig -SourceUri $disk.Id -CreateOption Copy -Location $region
$snapshotName = $imageName + "-" + $region + "-snap"
New-AzureRmSnapshot -ResourceGroupName $resourceGroupName -Snapshot $snapshot -SnapshotName $snapshotName
Copy the snapshot:
# Create the name of the snapshot, using the current region in the name.
$snapshotName = $imageName + "-" + $region + "-snap"
# Get the source snapshot
$snap = Get-AzureRmSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName
# Create a Shared Access Signature (SAS) for the source snapshot
$snapSasUrl = Grant-AzureRmSnapshotAccess -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName -DurationInSecond 3600 -Access Read
# Set up the target storage account in the other region
$targetStorageContext = (Get-AzureRmStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName).Context
New-AzureStorageContainer -Name $imageContainerName -Context $targetStorageContext -Permission Container
# Use the SAS URL to copy the blob to the target storage account (and thus region)
Start-AzureStorageBlobCopy -AbsoluteUri $snapSasUrl.AccessSAS -DestContainer $imageContainerName -DestContext $targetStorageContext -DestBlob $imageBlobName
Get-AzureStorageBlobCopyState -Container $imageContainerName -Blob $imageBlobName -Context $targetStorageContext -WaitForComplete
# Get the full URI to the blob
$osDiskVhdUri = ($targetStorageContext.BlobEndPoint + $imageContainerName + "/" + $imageBlobName)
# Build up the snapshot configuration, using the target storage account's resource ID
$snapshotConfig = New-AzureRmSnapshotConfig -AccountType StandardLRS `
-OsType Windows `
-Location $targetRegionName `
-CreateOption Import `
-SourceUri $osDiskVhdUri `
-StorageAccountId "/subscriptions/${sourceSubscriptionId}/resourceGroups/${resourceGroupName}/providers/Microsoft.Storage/storageAccounts/${storageAccountName}"
# Create the new snapshot in the target region
$snapshotName = $imageName + "-" + $targetRegionName + "-snap"
$snap2 = New-AzureRmSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName -Snapshot $snapshotConfig
Create the image:
<# -- In the second subscription, create a new Image from the copied snapshot --#>
Select-AzureRmSubscription -SubscriptionId $targetSubscriptionId
$snap = Get-AzureRmSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName
$imageConfig = New-AzureRmImageConfig -Location $destinationRegion
Set-AzureRmImageOsDisk -Image $imageConfig `
-OsType Windows `
-OsState Generalized `
-SnapshotId $snap.Id
New-AzureRmImage -ResourceGroupName $resourceGroupName `
-ImageName $imageName `
-Image $imageConfig
For more details, refer to this link.

Resources