How to output Azure Virtual Network Subnets to csv using powershell for single or multiple subscriptions - azure

I am new to powershell and trying to output subnet information for Azure Virtual Networks in either single or multiple subscriptions.
I can output to the console and get the results I'm looking for but struggling to get the same output to a csv file.
I understand that I need to create New Objects, etc. but can't get the correct syntax to work.
Could anyone help please.
Working code below....
$subs = Get-AzSubscription -SubscriptionID xxxxxxxxxxxxxxxx
foreach ($Sub in $Subs) {
$SelectSub = Select-AzSubscription -SubscriptionName $Sub.Name
$VNETs = Get-AzVirtualNetwork
foreach ($VNET in $VNETs) {
$Sub.Name
$VNET.Name
($VNET).AddressSpace.AddressPrefixes
($VNET).Subnets.Name
Write-Host " "
}
}

I think something like this will do the trick:
$subs = Get-AzSubscription -SubscriptionID xxxxxxxxxxxxxxxx
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
$networks = Get-AzVirtualNetwork | ForEach-Object {
New-Object PSObject -Property #{
name = $_.name
subnets = $_.subnets.name -join ';'
addressSpace = $_.AddressSpace.AddressPrefixes -join ';'
}
}
$networks | Export-Csv -NoTypeInformation file.csv
}
edit: previous version didnt really work, export-csv is a bit weird, i guess.

Related

Powershell hashtables values output Assembly not Value

Hi I'm trying to get vnet peering property using a Powershell script.
But I keep getting these values in teh table below, but when I print to screen they print fine.
These are values I keep getting:
RemoteVirtualNetwork
Microsoft.Azure.Commands.Network.Models.PSResourceId
RemoteVirtualNetworkAddressSpace
Microsoft.Azure.Commands.Network.Models.PSAddressSpace
#Login-AzAccount
$Subs = Get-AzSubscription
foreach ( $Sub in $Subs ) {
Set-AzContext -Subscription $Sub | Out-Null
$SubName = $sub.name
$vnets=get-azvirtualnetwork
foreach ($azvnet in $vnets){
$peer=get-AzVirtualNetworkPeering -VirtualNetworkName $azvnet.name -ResourceGroup $azvnet.ResourceGroupName | select-object ResourceGroupName,VirtualNetworkName,PeeringState,AllowVirtualNetworkAccess,AllowGatewayTransit,UseRemoteGateways,RemoteVirtualNetwork,RemoteVirtualNetworkAddressSpace
ForEach-Object{
New-Object PSObject -Property #{
ResourceGroupName = $peer.ResourceGroupName
VirtualNetworkName= $peer.VirtualNetworkName
PeeringState = $peer.PeeringState
PeeringSyncLevel = $peer.PeeringSyncLevel
AllowVirtualNetworkAccess = $peer.AllowVirtualNetworkAccess
AllowForwardedTraffic = $peer.AllowForwardedTraffic
AllowGatewayTransit = $peer.AllowGatewayTransit
UseRemoteGateways = $peer.UseRemoteGateways
RemoteVirtualNetwork = $peer.RemoteVirtualNetwork.Id.Split("/")[-1]
RemoteGateways = $peer.RemoteGateways
PeeredRemoteAddressSpace = $peer.PeeredRemoteAddressSpace
RemoteVirtualNetworkAddressSpace = $peer.RemoteVirtualNetworkAddressSpace | Select-Object -ExpandProperty AddressPrefixes
}
}
$peer|export-csv -path c:\personal\peers04.csv
}
}

Trying to list Azure Virtual Network and export to CSV using Powershell

I am trying to create a script that can list all the Azure virtual networks and export it into Csv using Powershell.
$day = Get-Date -Format " MMM-yyyy"
$path = "C:\Users\admin-vishal.singh\Desktop\Test\Report\"+ "$day-Vnet-Report.csv"
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
$resource_grps = Get-AzResourceGroup
foreach ($resource_grp in $resource_grps) {
$networks = Get-AzVirtualNetwork
foreach ($vnet in $networks)
{
$null = Get-AzVirtualNetwork |Select-Object SubscriptionName,ResourceGroupName,Name,AddressSpace,Subnets,SubnetAddressSpace,RouteTable | Export-CSV -Path $path -NoTypeInformation -Encoding ASCII -Append
}
}
}
I am not able to retrieve data in the right format & getting errors when retrieving data.
Below is snippet of data
Lots of values I am not able to retrieve like Subnet AddressSpace, Route Tables and Routes.
Building on what Jim Xu provided, you don't need to have a separate loop for each ResourceGroup. Get-AzVirtualNetwork will return all virtual networks for the entire subscription. Also, you'll need an expression for the SubscriptionName in the Select-Object, so the code would look like this:
foreach ($Sub in $Subs) {
Select-AzSubscription -SubscriptionName $Sub.Name | Out-Null
Get-AzVirtualNetwork |
Select-Object `
#{label='SubscriptionName'; expression={$Sub.Name}}, `
ResourceGroupName, `
Name, `
#{label='AddressSpace'; expression={$_.AddressSpace.AddressPrefixes}}, `
#{label='SubnetName'; expression={$_.Subnets.Name}}, `
#{label='SubnetAddressSpace'; expression={$_.Subnets.AddressPrefix}} |
Export-CSV -Path $path -NoTypeInformation -Encoding ASCII -Append
}
When we call export-csv command, the property values are converted to strings using the ToString() method. But the result of Get-AzVirtualNetwork are object, we cannot directly convert the value to string. For more details, please refer to here and here
So regarding the issue, I suggest you create a custom object with the information you need then save it into csv.
For exmaple
$vents =Get-AzVirtualNetwork|
Select-Object SubscriptionName,ResourceGroupName,Name, #{
label='AddressSpace'
expression={$_.AddressSpace.AddressPrefix}}, #{
label='SubnetName'
expression={$_.Subnets.Name}
}, #{
label='SubnetAddressSpace'
expression={$_.Subnets.AddressPrefix}
}
$vents | convertto-csv

How to get the list of azure servers having Auto-Shutdown disabled using PowerShell?

I want to get the list of azure servers having auto-shutdown disabled on them, I have the below script but the issue with the script is that it gets the list of RG's under the Subscription GUID but repeats the output after every loop.
Import-AzureRmContext -Path "$PSScriptRoot\AzureProfile.json"
Select-AzureRmSubscription -SubscriptionId {subscriptionId}
[array]$ResourceGroupArray = Get-AzureRMVm | Select-Object -Property ResourceGroupName, Name, VmId
foreach ($resourceGroup in $ResourceGroupArray){
$targetResourceId = (Get-AzureRmVM -ResourceGroupName $resourcegroup.ResourceGroupName -Name $resourceGroup.Name).Id
$shutdownInformation = (Get-AzureRmResource -ResourceGroupName $resourcegroup.ResourceGroupName -ResourceType Microsoft.DevTestLab/schedules -Expandproperties).Properties
Write-Host "ID: " $targetResourceId
$shutdownInformation
The output for each VM is displayed in the following format,
What I want is simple, I want the VM name and its status of Auto-shutdown to be displayed on the screen so that its easy for me to find out which all VM have auto-shutdown currently disabled on them.
Any help related to this would be helpful.
You just need to get the microsoft.devtestlab/schedules resource ID using:
/subscriptions/{subscriptionId}/resourceGroups/{rgName}/providers/microsoft.devtestlab/schedules/shutdown-computevm-{vmName}
Then iterate over all your VMs using Get-AzVM, Get the microsoft.devtestlab/schedules resource using Get-AzResource, then output VM name and status into a table using Format-Table.
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Set-AzContext -SubscriptionId $subscriptionId
& {
foreach ($vm in Get-AzVM) {
try {
$shutdownResource = Get-AzResource `
-ResourceId "/subscriptions/$subscriptionId/resourceGroups/$($vm.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($vm.Name)" `
-ErrorAction Stop
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $shutdownResource.Properties.status
}
}
catch {
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $_.Exception.Message
}
}
}
} | Format-Table -AutoSize
To set the context to the correct subscription, we can use Set-AzContext.
The above however is using the latest Az modules. You can do the same using the equivalent AzureRm modules.
$subscriptionId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
Set-AzureRmContext -SubscriptionId $subscriptionId
& {
foreach ($vm in Get-AzureRmVM) {
try {
$shutdownResource = Get-AzureRmResource `
-ResourceId "/subscriptions/$subscriptionId/resourceGroups/$($vm.ResourceGroupName)/providers/microsoft.devtestlab/schedules/shutdown-computevm-$($vm.Name)" `
-ErrorAction Stop
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $shutdownResource.Properties.status
}
}
catch {
[PSCustomObject]#{
VMName = $vm.Name
ShutdownStatus = $_.Exception.Message
}
}
}
} | Format-Table -AutoSize
Although I do recommend moving to the Az module since support for AzureRm is ending December 2020. You can read the documentation for more information about this.
The above code should give you an output similar to the following
VMName ShutdownStatus
------ --------------
vm1 Enabled
vm2 Disabled
Update
The Call operator & is used here to run the for loop as a script block. You can read more about this in about_Script_Blocks.
Try something like this to get the auto-shutdown status of all VMs. Instead of trying to get the schedules inside the loop, get all the ones in the subscription and match them based on the VM's full resource Id.
[array]$VMArray = Get-AzureRMVm | Select-Object -Property ResourceGroupName, Name, VmId, Id
$ShutdownInformation = (Get-AzureRmResource -ResourceType Microsoft.DevTestLab/schedules -Expandproperties).Properties
foreach($vm in $VMArray) {
$ShutdownStatus = "Not Configured"
$Schedule = $ShutdownInformation | Where-Object { $_.targetResourceId -eq $vm.Id } | Select -First 1
if($Schedule -ne $null) {
$ShutdownStatus = $Schedule.status
}
Write-Host $vm.VmId $ShutdownStatus
}

In Azure, To get Load balancer details in to csv file using powershell script

I wrote a powershell script in Azure DevOps pipeline to get Load Balancer details like FrontendIPConfigurationsName,FrontendIPAddress in to csv file. AM getting those details but FrontendIPConfigurationsNames which starts with same name like "ers-A1,ers-B1,ers-C1,ers-D1" are coming in same row. But I want to get them in different rows.Please suggest
$excel = #()
LBlist = Get-AZLoadBalancer | Where-Oject {$_.ResourceGroupName -clike '$(grp-wildcard)'} | Select-Object
foreach ($LB in LBlist)
$Array =""| Select-Object ResourceGroupName, FrontendIPConfigurationsName,FrontendIPAddress
$Array.ResourceGroupName =$LB.ResourcegroupName
$Array.FrontendIPConfigurationsName = ($LB.FrontendIpConfigurationsName.name -join ',')
$Array.FrontendIPAddress =($LB.FrontendIpConfigurations.PrivateIpAddress -join ',')
}
$excel +=$Array
$excel |Format-Table ResourceGroupName, FrontendIPConfigurationsName,FrontendIPAddress
$excel | Export-Csv -NTI -Path "($Build.ArtifactStagingDirectory)/LBlist.csv
You can do something similar to this to get the objects on separate rows.
$LBlist = Get-AZLoadBalancer | Where-Object { $_.ResourceGroupName -clike '$(grp-wildcard)' }
$LBlist | Export-Csv -NTI -Path "$(Build.ArtifactStagingDirectory)/LBlist.csv"
Mock for Get-AZLoadBalancer (not sure if it's entirely accurate as I've never used Az Powershell)
function Get-AZLoadBalancer() {
$obj = #(
[PSCustomObject] #{
ResourceGroupName = '$(grp-wildcard)'
FrontendIPConfigurationsName = 'ers-A1'
FrontEndIPAddress = '1.2.3.4'
},
[PSCustomObject] #{
ResourceGroupName = '$(grp-wildcard)'
FrontendIPConfigurationsName = 'ers-B1'
FrontEndIPAddress = '1.2.3.5'
}
)
return $obj
}

How to export VMData from azure across multiple subscriptions

I have been able to export VMData from a single azure subscription using the code below.
$VMs = Get-AzVM
$vmOutput = $VMs | ForEach-Object {
[PSCustomObject]#{
"VM Name" = $_.Name
"VM Profile" = $_.HardwareProfile.VmSize
"VM Type" = $_.StorageProfile.osDisk.osType
"VM Location" = $_.Location
"VM Resource Group Name" = $_.ResourceGroupName -join ','
}
}
$vmOutput | export-csv C:\Azure\VMdata.csv -delimiter ";" -force -notypeinformation
However, when using the code below to try and extract from across multiple subscriptions and get no results.
$azuresubs = Get-AzSubscription
$azureSubs.foreach{
Select-AzSubscription $_
$VMs = Get-AzVM
$vmOutput = $VMs | ForEach-Object {
[PSCustomObject]#{
"VM Name" = $_.Name
"VM Profile" = $_.HardwareProfile.VmSize
"VM Type" = $_.StorageProfile.osDisk.osType
"VM Location" = $_.Location
"VM Resource Group Name" = $_.ResourceGroupName -join ','
}
}
}
$vmOutput | export-csv C:\Azure\VMdata.csv -delimiter ";" -force -notypeinformation
Being new to powershell, I'm sure the syntax above is incorrect so any assistance would be much appreciated.
Thank you
i think what happens here is you overwrite your variable on each pass (and last pass happens to have no vms). so you need to append to it, not overwrite it. define it before loop:
$vmOutput = #()
and then append to it inside the loop
$vmOutput += $Vms | bla-bla-bla
final:
$vmOutput = #()
$azuresubs = Get-AzSubscription
$azureSubs.foreach{
Select-AzSubscription $_
$VMs = Get-AzVM
$vmOutput += $VMs | ForEach-Object {
[PSCustomObject]#{
xxx
}
}
}

Resources