Retrieve the NICs and the associated VMs in Azure - azure

I need to retrieve the NICs and the associated VMs in Azure
I've run the following Cmdlet:
Get-AzureRmNetworkInterface | Select Name, VirtualMachine
But, it only generate the names of the NICs but when it come to the Virtual Machine it displays Microsoft.Azure.Commands.Network.Models.PSResourceId, as shown in the following figure.
Please advise how to retrieve the actual name of the VM.

Please advise how to retrieve the actual name of the VM.
We could use the select-object to do that. It works correctly for me.
Get-AzureRmNetworkInterface | Select-Object -Property Name, #{Name="VMName";Expression = {$_.VirtualMachine.Id.tostring().substring($_.VirtualMachine.Id.tostring().lastindexof('/')+1)}}
Update : according to the comment
If we want to get the virtual network name we could use the command
Get-AzureRmVirtualNetwork
How to export the result in the same csv file. We could use out-file
Get-AzureRmVirtualNetwork | select Name |out-file $filePath -Append
Get-AzureRmNetworkInterface | Select-Object -Property Name, #{Name="VMName";Expression = {$_.VirtualMachine.Id.tostring().substring($_.VirtualMachine.Id.tostring().lastindexof('/')+1)}} |out-file $filePath -Append

Related

How to identify untagged resources forr tag name and value using azure powershell

I am looking for a PowerShell script for getting the list of resources not having specific tagname/value in Azure, am having the cmdlet for this as I mentioned below, but don’t know how to create a complete script using functions, parameters etc.
Please help.
Many thanks,
$Tags = #{"environment"="Terraform Demo"}
Get-AzResource | Where-Object $Tags -eq $null | Select-Object -Property Name, ResourceType
Please help me with this logic correct me if this not required. Thanks in advance.
If you want to receive resources that do not have any tags configured at all, you could use this query:
Get-AzResource | Where-Object {$_.Tags -eq $null}
If you want to receive resources that have the environment tag set to $nulll, you could use this query:
Get-AzResource | Where-Object {$_.Tags.environment -eq ''}
Contrarily, if you want to find resources that do not have the tag combination "environment" = "Terraform Demo" you could use:
Get-AzResource | Where-Object {$_.Tags.environment -ne 'Terraform Demo'}
You might also want to check switching to Resource Graph queries, since you would not have to change the context when searching across multiple subscriptions.
Checking for resources that do not have an environment tag configured would work like this:
Search-AzGraph -Query "Resources | where tags.environment=~'' | project name"
The latter requires the Az.ResourceGraph module. See here for details: https://learn.microsoft.com/en-us/azure/governance/resource-graph/samples/starter?tabs=azure-powershell#list-tag

How can i get a list of Azure VMS in my subscription showing cpus cores?

I need to extract a list of vms in our subscription which also shows the cpu cores each vm has , is there a way of doing this ?
You can use the below PowerShell Script, to pull the list of VM & their respective CPU Cores.
Connect-AzAccount
$vms=get-azvm | select -Property Name,ResourceGroupName,Location
foreach($vm in $vms){
$size = (Get-AzVM -ResourceGroupName $vm.ResourceGroupName -Name $vm.Name).HardwareProfile.VmSize
$output=Get-AzVMSize -Location $vm.Location|?{$_.Name -eq $size} | select -Property Name,NumberOfCores
Write-Output $vm.Name,$output|Format-Table -AutoSize
}
Here is the sample Output for reference:

How to get the status of a list of VM in Azure using Powershell Get-Azvm

I am trying to get a list of Azure vm statuses (Allocated,Deallocated). I am able to get it one at a time for a single vm. But when i have a list of VM's or when using wildcard's it fails to get the vm status. Any tips
$ResGrp= "resvmtest"
$action="start"
$vmList = Get-AzVM -ResourceGroupName $ResGrp -Name * -Status
foreach($vm in ($vmList | Select-Object #batch)){
Write-Host $vm.Statuses[1].DisplayStatus
}
I see that you were trying to display the VMs in batches. Unless you have VMs in the thousands, that's not necessary. I also no longer see the Statuses property in Get-AzVM cmdlet. Just try this:
$vmList = Get-AzVM -ResourceGroupName $ResGrp -Status
$vmList | Select-Object Name, PowerState, ProvisioningState # or any other properties you want to display
Either that or I'm not understanding your question.
Just try this :
Get-AzVm -ResourceGroupName <rg name> -Status | Select-Object Name, PowerState
This behaviour appears to have changed. Using the Status parameter now creates an object named Status and within that object.
One way to show the output:
select Name, #{n='New';e={($_.Statuses | where Code -eq 'PowerState/running').DisplayStatus}}

How to get the NIC details for Application Security Group / Resource Group

I'm looking a PowerShell command which is used to list out the relationship between the network interface card and its associated application security group / resources group. I use the following commands and it only displays the VMName, IPAddress. The Application Security Group cannot be shown up.
I already use -ExpandProperty ApplicationSecurityGroups but still doesn't work.
$nics =Get-AzureRmNetworkInterface -ResourceGroupName "My-RG"
foreach($nic in $nics)
{
$vm = $vms | where-object -Property Id -EQ $nic.VirtualMachine.id
$Name = $nic.Name
$prv = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAddress
$alloc = $nic.IpConfigurations | select-object -ExpandProperty PrivateIpAllocationMethod
$asc = $nic.IpConfigurations | select-object -ExpandProperty ApplicationSecurityGroups
Write-Output "$Name, $prv , $asc"
}
It is quite hard to retrospectively query members of an ASG, the property is contained in arrays within arrays in the NIC configuration. I found an AZ cli command to retrieve this, hope it saves some time.
az network nic list --query '[].{Name:name,ASG:ipConfigurations[0].applicationSecurityGroups[].id}'
I've just tested your commands and I can get the application security group successfully, from a machine that is configured with an ASG. However, that will only work if you have put the VM in an ASG, ASG's are there to provide micro-segmentation inside a subnet, so you can group your app servers, DBs etc. together and apply NSG rules to groups rather than single servers.
If instead, you want to know what NSG the VM is in, you need a different command. NSG's are the resource that attaches to a VM or NIC and acts like a firewall. If you want that then you need to run:
$nsg = $nic | select-object -ExpandProperty NetworkSecurityGroup
However, this is only going to get you the NSG applied to the VM, you can also apply these at the VM level, so you are better running this command:
$effectiveRules=Get-AzureRmEffectiveNetworkSecurityGroup -NetworkInterfaceName <nicName> -ResourceGroupName <resourceGroup>
$effectiveRules.NetworSecurityGroup
This will list all NSGs applied either at NIC or Subnet level.
The thing is that you can only get the ASG information from property IpConfigurationsText as a string, so you'll need to update your query to this:
$nics = Get-AzureRmNetworkInterface -ResourceGroupName "My-RG"
foreach($nic in $nics)
{
$GetAzureNIC = Get-AzureRmNetworkInterface -ResourceGroupName "My-RG" -Name $nic.Name
$Name = $nic.Name
$prv = $nic.IpConfigurations.PrivateIpAddress
$alloc = $nic.IpConfigurations.PrivateIpAllocationMethod
$asgResourceID = ($GetAzureNIC.IpConfigurationsText | ConvertFrom-Json).ApplicationSecurityGroups.Id
$asgName = (Get-AzureRmResource -ResourceId $asgResourceID).Name
Write-Output "$Name, $prv, $alloc, $asgName, $asgResourceID"
}
EDIT: I've noticed that you also want to get the allocation method but don't use it in the Write-Output and updated the query to include both ASG name and ASG resource ID, pick whichever you need.

What am I Missing in PowerShell in Azure Automation that prevents Start-AzureVM from working?

I have the following PS script that runs fine locally:
Get-AzureVM | Where-Object { $_.Name -eq "my-server-selector" } | select name | ForEach-Object {
Write-Output $_.Name
Start-AzureVM $_.Name $_.Name
}
In the context of my local PS console, I add my subscription info and the code executes without a problem; all VMs are printed to the output and the servers are started up.
When I move it to the cloud I need to do a few other things, namely, bring the subscription in scope. I do that by creating the credential asset in the portal, adding the account to my script via said credentials, then selecting the correct subscription in the script. I also wrap it in a workflow (there are aspects I intent to parametrize at a later date).
The final code is as follows:
workflow StartServer
{
$credential = GetAutomationPSCredential -Name "credential-asset-name"
Add-AzureAccount -Credential $credential
Select-AzureSubscription -SubscriptionName "subscription-name"
Write-Output "Starting the server."
Get-AzureVM | Where-Object { $_.Name -Contains "my-server-selector" } | select name | ForEach-Object {
Write-Output $_.Name
Start-AzureVM $_.Name $_.Name
}
Write-Output "Execution Complete."
}
If I remove the Start-AzureVM command, the workflow runs as expected. I get a listing of all the matching VMs printed out. If I attempt to put the command back in, I get the following error:
Parameter set cannot be resolved using the specified named parameters.
So, things I think I know:
the credentials are working as I'm getting the correct list of VMs
the subscription is being correctly set, as it's dumped to the output
the inner part of the script works on a local powershell console without any changes
Can anyone provide any ideas as to what needs to be done differently in an Azure Automation workflow to get this to work?
The fix was to be more explicit in the naming of parameters, both in the filter for the Where-Object as well as in the call to Start-AzureVM. I'm not sure why this would make a difference; as I said, the call to write the names of the servers worked without the explicit parameter name, but low and behold, here it works with it set.
The final code of the inner block is as follows:
Get-AzureVM | Where-Object -FilterScript { $_.Name -Contains "my-server-selector" } | select name | ForEach-Object {
Write-Output $_.Name
Start-AzureVM -ServiceName $_.Name -Name $_.Name
}
Thanks to #DexterPOSH on Twitter for the direction on -FilterScript.
Please take a look at http://azure.microsoft.com/blog/2014/11/25/introducing-the-azure-automation-script-converter/ which talks about this exact issue. When authoring Powershell in the ISE to move into Azure Automation, make sure you are testing / writing as Powershell Workflow in the ISE, since Powershell workflow has some differences vs Powershell script.
Or, if you need to take PS script and use it in Azure Automation, make sure you import the script, not copy paste it in. Azure Automation will then convert the PS script to PS Workflow for you. The link above has more details on this.

Resources