Add-Member to Az object - azure

I'm writing a function that I can use for thumbing through all my subscriptions in azure and gather environment details (for auditing or bulk updating) and I'm trying to append the subscription the item came from into the return object so I can keep things sorted. This is the beginning of the function I'm building:
Function Find-AllAzResourceByType
{
Param (
[ValidateSet('SqlServer','KeyVault')]
[String]$type
)
ForEach($Subscription in (Get-AzSubscription))
{
Set-AzContext $subscription.Name | out-null
Switch ($type)
{
"SqlServer" {$return += Get-AzSqlServer | Add-Member 'Subscription' $subscription.Name}
"KeyVault" {$return += Get-AzKeyVault}
}
}
Return $return
}
I have tried several ways of calling the add-member:
Get-AzSqlServer | ForEach {$_ | Add-Member 'Subscription' $subscription.Name}
Get-AzSqlServer | ForEach {Add-Member -MemberType NoteProperty -Name 'Subscription' -value $subscription.Name -inputobject $_}
Get-AzSqlServer | Select-Object *,$Subscription.Name
and nothing I'm trying seems to work. I'm sure this is something obvious I'm missing but I'm failing to see it... anyone got any ideas?

If all you're interested in is finding about the subscription id of the resource, you don't really need to do all of this. You can extract the subscription id from the ResourceId property.
When I execute Get-AzSqlServer against my Azure Subscription, for each SQL Server I get the resource id in the following format:
/subscriptions/<my-subscription-id>/resourceGroups/<my-resource-group-name>/providers/Microsoft.Sql/servers/<my-database-server-name>
I can easily parse the above string to get the subscription id.

Related

How to get list of all Azure subscriptions and resources using powershell (in specific format)

I am trying to execute below powershell script to get list of all Azure subscriptions and resource details,
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
Set-AzContext -SubscriptionId $_.SubscriptionId
Get-AzResource | Select Name,ResourceGroupName,Location,Type
} | Export-Csv azureinventory.csv
However, its just dumping the data in one column in mentioned CSV file. I need each column to display Subscription name, Subscription ID, associated resource name, resource groupname, location, Type.
Please help to update the script accordingly.
Below Script will help you to get the details of your current subscription name, tenant id, environment, account name(or select your subscription after logging) and also the resource groups in that subscription, each resource group name, type, location of each resource available in that resource group, where you can export into excel sheet with a specific format like:
Script:
$ErrorActionPreference = "Stop"
try {
Connect-AZAccount
Set-AzContext -SubscriptionName 'Your Subscription Name'
$rgs = Get-AzResourceGroup
foreach ($rg in $rgs.ResourceGroupName)
{
Write-Output "Checking Resource Group: $rg"
Get-AzResource -ResourceGroupName $rg | Select Name, ResourceGroupName, Type, Location | Export-Csv .\AzureResources.csv -Append -Force -NoTypeInformation
} }
catch {
Write-Host "$($_.Exception.Message)" -BackgroundColor DarkRed
}
And the Output is:
It will check the resource groups existing or not. After that, open the AzureResources.csv file exported in the path where you executed your script in the PowerShell.
The exported file shows the data of resource group name, each resource name, its type and location in the tabular format.
I have updated the script and it is not tested. the parameter value can be different here. Kindly change it by verifying it from Get-Azresource.
$resources = #()
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$subscriptionId = $_.SubscriptionId
Get-AzResource | ForEach-Object {
$resources += [PSCustomObject]#{
SubscriptionName = $subscriptionName
SubscriptionId = $subscriptionId
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
Location = $_.Location
}
}
}
$resources | Export-csv c:\sompeath\somename.csv

Using PowerShell, How to get list of all Azure subscriptions having Azure Data factory Resource in it?

I want to retrieve the list of subscriptions having Azure Data Factory resource in it. I want to use PowerShell and get the subscription list and ADF list.
I have tried Get-AzSubscription, but it does not contain filter for resource type i.e. Microsoft.DataFactory/factories. This filter can be added to only Get-AzResource.
Get-AzSubscription Module
Get-AzResource Module
Ok here you are:
$resType = "Microsoft.DataFactory/factories"
$resTypeName = "DataFactory"
Get-AzSubscription | ForEach-Object {
$subscriptionName = $_.Name
$tenantId = $_.TenantId
Set-AzContext -SubscriptionId $_.SubscriptionId -TenantId $_.TenantId
(Get-AzResource -ResourceType $ResType) | ForEach-Object {
[PSCustomObject] #{
true_sub = $subscriptionName
}
} | get-unique
} | Select-String 'true_sub' | ForEach-Object{ "Found_" + "$resTypeName" + "_In_Subscription= $($subscriptionName)"}
EDIT: Added variables to make it easily reusable for any resource type.
I used the code available here and here to create a custom one based on the requirements. Tested in my environment - it seems to work as expected.
I should disclose that I'm not an advanced PowerShell user, so the code I'm providing could really be sub-optimal.

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

Azure Powershell Script Force FTPS Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter

I am currently trying to run a script in Azure that would go through all of our Web Apps and turn on FTPS.
This is what I currently have
$Subscriptions = Get-AzSubscription
foreach ($sub in $Subscriptions) {
Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext
$GetName = (Get-AzWebApp).Name
$GetRG = (Get-AzWebApp).ResourceGroup
Set-AzWebapp -Name $GetName -ResourceGroupName $GetRG -FtpsState FtpsOnly
}
Set-AzWebApp : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Name'. Specified
method is not supported.
I currently am getting this error, which I dont understand as .Name and .ResourceGroup, from my understanding are already strings. I am very new to powershell so any help would be greatly appreciated. Thanks everyone!
Your example calls Az-WebApp with no parameters, which gets all apps in the subscription - this is a collection - and then tries to get the Name of that result, which is what causes your error.
You need to loop through each app in the subscription as well as looping through each subscription, as in:
# Get all subscriptions and iterate them
Get-AzSubscription | ForEach-Object {
Set-AzContext -SubscriptionName $_.Name
# Get all web apps in the subscription and iterate them
Get-AzWebApp | ForEach-Object {
Set-AzWebApp -Name $_.Name -ResourceGroupName $_.ResourceGroup -FtpsState FtpsOnly
}
}

Powershell script to get all parent resources

Good day,
I am trying to figure out a way to get all the parent objects in my azure subcription to a csv from Azure.
By parent object, I am refering to objects like, VMs, Webapps, Kubernetes Clusters, ect. I want to strip away any data that is deemed illrevelant like Nics, PIPs, storage disks, ect. I am not super proficent in powershell. and I am not sure how to tackle this.
I have an azure workbook that I created that gives a good overview in a nice format, I would like to export the entire workbook for offline viewing but that doesn't seem to be possible.
Any help would be greatly appreiciated.
So, what's an "interesting" resource to you may not be to the next person, and vice versa - in some cases, for example, I may set up NICs independently of my VMs, and want to see them. I don't think there's a way to automatically get just the things you want. What you could do is create a list of resources that are interesting to you (by type), and then use Powershell to create your report:
Get 'em all and filter 'em
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
Get-AzResource | ForEach-Object {
if ($resourceTypes -contains $_.resourceType) {
$resources += [PSCustomObject] #{
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
$resources | Sort-Object ResourceType, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Get 'em type by type (this one loops through subscriptions to which you have access, will print out a line with the current context on each subscription, will restore context to the current subscription when done)
$resourceTypes = #(
'Microsoft.Compute/virtualMachines',
'Microsoft.Sql/servers',
'Microsoft.Sql/servers/databases'
)
$resources = #()
$currentContext = Get-AzContext
try {
Get-AzSubscription | ForEach-Object {
$_ | Set-AzContext
$subscriptionName = $_.Name
$resourceTypes | ForEach-Object {
Get-AzResource -ResourceType $_ | ForEach-Object {
$resources += [PSCustomObject] #{
SubscriptionName = $subscriptionName
ResourceGroupName = $_.ResourceGroupName
ResourceName = $_.ResourceName
ResourceType = $_.ResourceType
}
}
}
}
} finally {
$currentContext | Set-AzContext
}
$resources | Sort-Object ResourceType, SubscriptionName, ResourceGroupName, ResourceName |
Export-Csv -Path <path to>\resources.csv
Whichever approach you choose, just customize the $resourceTypes list to contain just the resource types that you want.
To get a list of resource types, I do something like this:
Get-AzResourceProvider -ProviderNamespace Microsoft.Sql |
Select ProviderNamespace -Expand ResourceTypes |
Select #{ L="Provider"; E={ "$($_.ProviderNameSpace)/$($_.ResourceTypeName)" } }
Leave off the -ProviderNamespace Microsoft.Sql if you want to get all resource types, but that will be a long list.

Resources