how to get ll azure vms report on email using automation runbook acccount ?
hello all ,
i am using below powershell script to get all azure vms report on email like assigned user name ,current vms staus on email
Azure Virtual Machines
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-15T16:29:04.61+00:00 Hi Madhukar Mali,
Welcome to the Microsoft Q&A Platform. Thank you for posting your query here. We are looking into it and will get back to you soon.
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-15T18:34:50.4133333+00:00 Hi Madhukar Mali,
Welcome to the Microsoft Q&A Platform.
I understand that you are using PowerShell script to get all azure VM's report on email like assigned username, current VM's status on email.
It will help you to create a script that retrieves the necessary information and sends it via email. Follow these steps to resolve the issue.
1.Connect to Azure
Connect-AzAccount
2.Get all VMs in the subscription$vms = Get-AzVM
3.Create an array to store VM details$vmReport = @()
foreach ($vm in $vms) {
//Retrieve assigned user (if any)
$assignedUser = (Get-AzRoleAssignment -ObjectId $vm.Identity.PrincipalId).DisplayName
$vmInfo = [PSCustomObject]@{ VMName = $vm.Name
ResourceGroup = $vm.ResourceGroupName
Status = $vm.PowerState
AssignedUser = if ($assignedUser) { $assignedUser } else { "No assigned user" } } $vmReport += $vmInfo }
4.Convert the report to HTML
$htmlReport = $vmReport | ConvertTo-Html -Fragment -Property VMName, ResourceGroup, Status, AssignedUser
5.Email parameters
$smtpServer = "smtp.your-email-provider.com" # Replace with your SMTP server
$smtpPort = 587 #Adjust if necessary
$from = "you@example.com" # Your email address
$to = "recipient@example.com" # Recipient email address
$subject = "Azure VM Report"
$body = "<h2>Azure VM Report</h2>" + $htmlReport
6.Send the email Send-MailMessage -From $from -To $to -Subject $subject -Body $body -BodyAsHtml -SmtpServer $smtpServer -Port $smtpPort -UseSsl
For this Report sent successfully.Please check for further reference: Send an email from an Automation runbook
How to get list of all Azure VMs in Powershell
Manage runbooks in Azure AutomationIf you feel that your quires have been resolved, if it was helpful, please click "Upvote" on his post to let us know.
-
Madhukar Mali 0 Reputation points
2024-10-16T05:37:01.7066667+00:00 Hello Lijitha B ,
i am getting below error while running your bove script
Failed
ParserError: C:\Temp\l4vszujt.wk3\30b02eeb-7c7c-4794-b30a-6c34f5b8418f.ps1:22 Line | 22 | … er) { $assignedUser } else { "No assigned user" } } $vmReport += $vmI … | ~~~~~~~~~ | Unexpected token '$vmReport' in expression or statement.
-
Madhukar Mali 0 Reputation points
2024-10-16T05:38:13.0733333+00:00 Hello Lijitha B ,
i am getting below error while using your script
Failed
ParserError: C:\Temp\l4vszujt.wk3\30b02eeb-7c7c-4794-b30a-6c34f5b8418f.ps1:22 Line | 22 | … er) { $assignedUser } else { "No assigned user" } } $vmReport += $vmI … | ~~~~~~~~~ | Unexpected token '$vmReport' in expression or statement.
Thanks,
Madhukar
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-16T17:42:36.1766667+00:00 Hi Madhukar Mali,
Thanks for your response,
Do you have any other script with you, As you mention in the first question, is that working could you please share if you are getting error on your own script. And also please try the below script and let us know.# Connect to Azure Connect-AzAccount -Identity # Get all VMs $vms = Get-AzVM # Format the VM information $vmReport = $vms | ForEach-Object { "VM Name: $($_.Name), Resource Group: $($_.ResourceGroupName), Location: $($_.Location), Status: $($_.PowerState)" } | Out-String # SendGrid API details $sendGridApiKey = Get-AzKeyVaultSecret -VaultName "<YourKeyVaultName>" -Name "SendGridAPIKey" | Select-Object -ExpandProperty SecretValueText $sendGridUrl = "https://api.sendgrid.com/v3/mail/send" $emailBody = @{ personalizations = @(@{to = @(@{email = "<RecipientEmail>"})}) from = @{email = "<SenderEmail>"} subject = "Azure VMs Report" content = @(@{type = "text/plain"; value = $vmReport}) } # Send the email Invoke-RestMethod -Uri $sendGridUrl -Method Post -Headers @{Authorization = "Bearer $sendGridApiKey"} -Body ($emailBody | ConvertTo-Json -Depth 3)
If you feel that your quires have been resolved, if it was helpful, please click "Upvote" on his post to let us know.
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-17T16:46:31.5033333+00:00 Hi Madhukar Mali,
Just checking in to see if you have got a chance to see the comment posted in resolving the issue.If it was helpful, please click "Upvote" on his post to let us know.
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-18T15:27:33.9266667+00:00 Hi Madhukar Mali,
Did you get a chance to look into the above comment? Let us know if the issue has been resolved.
-
Madhukar Mali 0 Reputation points
2024-10-22T08:58:34.73+00:00 i am using below script also i m getting email
problem :- i am getting all detail but not vm status like below
VM Name: Azure-AVD01-0, Resource Group: AZUREAVDTEST, Location: eastus, Status: VM Name: AzureAVD-0, Resource Group: AZUREAVDTEST, Location: eastus, Status: VM Name: AzureAVD-01-0, Resource Group: AZUREAVDTEST, Location: eastus, Status:
Connect to Azure
Connect-AzAccount -Identity
Get all VMs
$vms = Get-AzVM
Format the VM information
$vmReport = $vms | ForEach-Object {
"VM Name: $($.Name), Resource Group: $($.ResourceGroupName), Location: $($.Location), Status: $($.PowerState)"
} | Out-String
SMTP details
$smtpServer = "smtp.office365.com" # Replace with your SMTP server
$smtpPort = 587 # Common port for TLS
$fromEmail = "adc@com" # Replace with your email
$toEmail = "abc@com" # Replace with recipient email
$smtpUser = "cde@com" # Your email for SMTP authentication
$smtpPassword = "fhdgdfsgdhd" # Your email password (consider using a secure method to store/retrieve this)
Create the email message
$emailMessage = @{
SmtpServer = $smtpServer
Port = $smtpPort
From = $fromEmail
To = $toEmail
Subject = "Azure VMs Report"
Body = $vmReport
UseSsl = $true
Credential = New-Object System.Management.Automation.PSCredential ($smtpUser, (ConvertTo-SecureString $smtpPassword -AsPlainText -Force))
}
Send the email
try {
Send-MailMessage @emailMessage
Write-Output "Email sent successfully."
} catch {
Write-Error "Failed to send email: $_"
}
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-22T13:15:00.17+00:00 Hi Madhukar Mali,
Thank you for your reply!
When you run the command
Get-AzVM
, it returns a collection of VM objects. Each VM object contains various properties, such as: --
Name
: The name of the VM. -
ResourceGroupName
: The name of the resource group containing the VM. -
Location
: The geographical location of the VM.
However, it does not contain a direct property called
PowerState
. The state of a VM (whether it’s running, stopped, or deallocated) is not included in the standard properties of the VM object returned byGet-AzVM
. $($.PowerState) is incorrect becausePowerState
is not a property of the VM object directly. Get-AzVMThe power state represents the last known state of the VM. Power states and billing
The provisioning state is the status of a user-initiated, control-plane operation on the VM. These states are separate from the power state of a VM. Provisioning states
If it was helpful, please click "Upvote" on his post to let us know.
-
-
Madhukar Mali 0 Reputation points
2024-10-23T09:08:59.05+00:00 Hello Lijitha B ,
Good Day,
need small help below script working fine as exptected but problem is that only assigned vm user name not showing below script may i know why ?can you please help me urgently ?
Connect to Azure
Connect-AzAccount -Identity
Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All"
Get all VMs with their statuses
$vms = Get-AzVM -Status
Start building the HTML report
$vmReportHtml = @"
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Azure VMs Report</h2>
<table>
<tr>
<th>VM Name</th>
<th>Resource Group</th>
<th>Location</th>
<th>Status</th>
<th>Assigned Users</th>
</tr>
"@
Add VM information to the HTML report
foreach ($vm in $vms) {
$powerState = $vm.PowerState -replace "PowerState/", "" # Clean up the string if needed
Initialize assigned users variable
$assignedUsers = @()
Debugging: Output current VM details
Write-Output "Processing VM: $($vm.Name), Resource Group: $($vm.ResourceGroupName), Location: $($vm.Location)"
Get the role assignments for the VM
$roleAssignments = Get-AzRoleAssignment -Scope $vm.Id
if ($roleAssignments) {
foreach ($role in $roleAssignments) {
if ($role.PrincipalType -eq "User") {
try {
Get the user details from Microsoft Graph
$aadUser = Get-MgUser -UserId $role.PrincipalId
if ($aadUser) {
$assignedUsers += $aadUser.DisplayName # Store assigned user name
Write-Output "Assigned User Found: $($aadUser.DisplayName)" # Debugging output
} else {
Write-Output "No user found for PrincipalId: $($role.PrincipalId)"
}
} catch {
Write-Error "Failed to retrieve Azure AD user info for PrincipalId: $($role.PrincipalId): $_"
}
} else {
Write-Output "Skipping non-user principal type: $($role.PrincipalType)"
}
}
} else {
Write-Output "No role assignments found for VM: $($vm.Name)"
}
Prepare assigned users list as a comma-separated string
$assignedUsersList = $assignedUsers -join ', ' -replace '^, |, $', '' # Remove any leading/trailing commas
Add VM information and assigned users to the HTML report
$vmReportHtml += "<tr>
<td>$($vm.Name)</td>
<td>$($vm.ResourceGroupName)</td>
<td>$($vm.Location)</td>
<td>$powerState</td>
<td>$assignedUsersList</td>
</tr>"
}
Close the HTML tags
$vmReportHtml += @"
</table>
</body>
</html>
"@
Output the VM report for debugging (optional)
Write-Output $vmReportHtml
SMTP details
$smtpServer = "smtp.office365.com" # Replace with your SMTP server
$smtpPort = 587 # Common port for TLS
$fromEmail = "gdfsds@com" # Replace with your email
$toEmail = "mmali@relatient.com" # Replace with recipient email
$smtpUser = "dgsfs@re.com" # Your email for SMTP authentication
$smtpPassword = "dhgsfsfdhdgdfd" # Your email password (consider using a secure method to store/retrieve this)
Create the email message
$emailMessage = @{
SmtpServer = $smtpServer
Port = $smtpPort
From = $fromEmail
To = $toEmail
Subject = "Azure VMs Report"
Body = $vmReportHtml
UseSsl = $true
Credential = New-Object System.Management.Automation.PSCredential ($smtpUser, (ConvertTo-SecureString $smtpPassword -AsPlainText -Force))
BodyAsHtml = $true # This indicates that the body is HTML
}
Send the email
try {
Send-MailMessage @emailMessage
Write-Output "Email sent successfully."
} catch {
Write-Error "Failed to send email: $_"
}
-
Lijitha B 495 Reputation points • Microsoft Vendor
2024-10-23T16:14:46.8866667+00:00 Hi Madhukar Mali,
Thanks for your information.
To get the assigned user VM name in Azure using PowerShell, you can use the
Get-AzRoleAssignment
cmdlet. This cmdlet lists all the roles that are assigned to a specified user and the roles that are assigned to the groups to which the user belongs. IAM added user you can list using Get-AzRoleAssignment ( https://learn.microsoft.com/en-us/azure/role-based-access-control/tutorial-role-assignments-user-powershell#list-access )
For OS added users we need to query from the OS.Since there isn't a built-in command that directly provides assigned user VM name, you'll need to create a custom script that meets your specific requirements.
If you have any further queries, do let us know.
Sign in to comment