Harj
Harj

Reputation: 35

Create 2 publicIPs and assign to nics

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

Upvotes: 1

Views: 130

Answers (2)

Jack Jia
Jack Jia

Reputation: 5559

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.

Upvotes: 2

4c74356b41
4c74356b41

Reputation: 72151

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}

Upvotes: 1

Related Questions