Hi Sheetal Jain,
Welcome to the Microsoft Q&A Platform! Thank you for asking your question here
Based on your query,
When you see the error
"Index was out of range. Must be non-negative and less than the size of the collection",
To understand the scenario elaborating little bit for more to address the issue for you in future as well
Example Scenario
When you're working with a list or array, the number you use to access an element must be zero or a positive number. Negative numbers won't work. Additionally, the number you use must be within the range of the list. For example, if your list has 5 items, you can use numbers 0 through 4. Trying to use a number outside this range, like 5 or higher, will cause an error because those positions don't exist in the list
If you know all these things already means that would be great.!
Troubleshooting
To address this issue make try to check make sure the virtual network named EXSrvrVnet
and its subnets are set up properly and being referenced correctly. You need to confirm that the first subnet in the list ($vnet.Subnets[0].Id
) exists and isn't empty. Also, ensure that the availability set called dcAvailabilitySet
has been created and can be retrieved without issues. Finally, verify that the network interface ($nic
) is being created with the correct subnet ID. By checking these key points,
use some debug output line to verify the resource exist or not by using below commands
Example:
$nic = New-AZNetworkInterface -Name adVM-NIC -ResourceGroupName $rgName -Location $locName -SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -PrivateIpAddress 10.0.0.4 Write-Output "Network Interface: $($nic)"
And also handle this case use the exception case get to know where the issue cause handling in power shell techniques to understand Please refer the below documentation
Everything you wanted to know about exceptions
about_Try_Catch_Finally
Please let me know if you have any further questions or if you are still experiencing the issue. Tag me in a comment, and I will be happy to help. Feel free to ask if you need any additional information. I am always here to assist you as needed.
If you found this information helpful, please click an accepting the answer and 👍"Upvote" on my post for other community member's reference