get-quarantinemessages in Azure Automation - azure

If i try the script below in Azure Automation, I get the error Get-QuarantineMessages is not recognized ...
This cmdlet dont work in Azure Automation?
$MyCredential = "O365Credential"
$subject = "Mail send from Azure Automation using Office 365"
$userid='xistoso#xistoso.ca'
# Get the PowerShell credential and prints its properties
$Cred = Get-AutomationPSCredential -Name $MyCredential
if ($Cred -eq $null)
{
$Body = Write-Output "Credential entered: $MyCredential does not exist in the automation service. Please create one `n"
}
else
{
$ExchangeOnlineSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Cred -Authentication Basic -AllowRedirection -Name $ConnectionName
Import-Module (Import-PSSession -Session $ExchangeOnlineSession -AllowClobber -DisableNameChecking) -Global
$today = get-date
$yesterday = (get-date).AddHours(-1)
$Body = Get-QuarantineMessage -Direction Inbound -StartReceivedDate $yesterday -EndReceivedDate $today
<#$CredUsername = $Cred.UserName
$CredPassword = $Cred.GetNetworkCredential().Password
Write-Output "-------------------------------------------------------------------------"
Write-Output "Credential Properties: "
Write-Output "Username: $CredUsername"
Write-Output "Password: *************** `n"
Write-Output "-------------------------------------------------------------------------"
# Write-Output "Password: $CredPassword `n" 3#>
}
Send-MailMessage -To 'xisto#xisto.com' -Subject $subject -Body $Body -UseSsl -Port 587 -SmtpServer 'smtp.office365.com' -From $userid -BodyAsHtml -Credential $Cred
Write-Output "Mail is now send `n"
Write-Output "-------------------------------------------------------------------------"
Remove-PSSession $ExchangeOnlineSession

Related

Azure Runbook | Sending attachments from my Azure Storage Account in Transactional Emails

I have an Azure Runbook script set up for transaction emails, the SMTP server details, & the from and to emails redacted for security.
For some reason, PowerShell is not seeing the file with which I want to send as an attachment, can anyone see where I am going wrong?
I have included a screenshot as proof that I have the correct file (I believe they're called 'blobs'?) name, storage account name and container name
Below is the Runbook PowerShell script, along with the error messages upon testing the email.
All the best,
===================RUNBOOK POWERSHELL CODE===========================
$Username ="xxx"
$Password = ConvertTo-SecureString "xxx" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$SMTPServer = "xxx"
$EmailFrom = "xxx"
[string[]]$EmailTo = "xxx"
$Subject = "xxx"
# Setting the Azure Storage Context,recommedation is to read sastoken from Runbook assets for security purpose.
$context = New-AzureStorageContext -StorageAccountName "expertadvisers" -SasToken "?sv=2019-12-12&ss=bfqt&srt=c&sp=rwdlacupx&se=2021-01-20T17:01:17Z&st=2021-01-20T09:01:17Z&spr=https&sig=PpozvhXnD6k4knwLLpyJvMF0vpnSZATabreYTzr0s2k%3D"
#Get the blob contents from storage container and store it local destination .
Get-AzureStorageBlob -Container "notificationcontainer" -Blob "test_file.docx" -Context $context | Get-AzureStorageBlobContent -force -Destination .
#Get contents of the file
[string[]] $attachment = "test_file.docx"
$Body = "TEST MESSAGE"
Send-MailMessage -smtpServer $SMTPServer -Attachment $attachment -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body -Priority High -DeliveryNotificationOption OnSuccess -BodyAsHtml
Write-Output ("Email sent succesfully.")
===================ERROR MESSAGE===========================
Get-AzureStorageBlob : The remote server returned an error: (403) Forbidden. HTTP Status Code: 403 - HTTP Error
Message: Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly
including the signature.
At line:19 char:1
+ Get-AzureStorageBlob -Container "notificationcontainer" -Blob "test_f ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzureStorageBlob], StorageException
+ FullyQualifiedErrorId :
StorageException,Microsoft.WindowsAzure.Commands.Storage.Blob.Cmdlet.GetAzureStorageBlobCommand
Send-MailMessage : Could not find file 'C:\Temp\pyxr0xjf.rej\test_file.docx'.
At line:32 char:1
+ Send-MailMessage -smtpServer $SMTPServer -Attachment $attachment -Cre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
Regarding the issue, please refer to the following steps
Create SAS token via protal
Script
$Username =""
$Password = ConvertTo-SecureString "" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$Subject = "test"
$To=""
$Body = "This is an automated mail send from Azure Automation relaying mail using Office 365."
$Context = New-AzureStorageContext -StorageAccountName "andyprivate" -SasToken "<the sas token you created in step1>"
$a=Get-AzureStorageBlobContent -Container "output" -Blob "test.txt" -Context $Context
$attachment = $a.Name
Send-MailMessage `
-To $To `
-Subject $Subject `
-Body $Body `
-UseSsl `
-Port 587 `
-SmtpServer 'smtp.office365.com' `
-From $Username `
-Attachments $attachment `
-BodyAsHtml `
-Credential $credential

Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials

While logging into the Azure account through powershell, I am getting the error -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.
I need to understand when this error comes?
[string]$TenantID,
[string]$ApplicationID,
[string]$SecretKey,
[string]$ProcessInstanceID,
[string]$Endpoint
)
$securePassword = ConvertTo-SecureString -String $SecretKey -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($ApplicationID, $securePassword)
$profilePath = "D:\" + $ProcessInstanceID + "_azureProfile.json"
Clear-AzureRmContext -Scope Process
$azureok = $null
while ($azureok -eq $null) {
if($Endpoint -match "china"){
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -Environment AzureChinaCloud -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
else{
Connect-AzureRmAccount -ServicePrincipal -TenantId $TenantID -Credential $cred -ea silentlycontinue -wa silentlycontinue -ev errorvar | out-null
}
if ($errorvar.exception -ne $null) {
if ($errorvar.exception.message -eq "An error occurred while sending the request.") {
Start-sleep -s 10
$error.clear()
} else {
break
}
} else {
$azureok = $true
}
}
Save-AzureRmContext -Path $profilePath ````
Error message -
Login-AzureRmAccount : -Credential parameter can only be used with Organization ID credentials.

Azure Analytics Database with automate Backup

The powershell is used to automate the backup of AAS instance.
The instance have Multi-factor authentication and I think that is the problem.
Powershell:
$TenantId = "TenentID"
$Cred = Get-AutomationPSCredential -Name 'SSASModelBackup'
$Server = "ServerName"
$RolloutEnvironment = "location.asazure.windows.net"
$ResourceGroup = "ReourceGroupName"
#Create Credentials to convertToSecureString
$applicationId = "applicationId "
$securePassword = "securePassword " | ConvertTo-SecureString -AsPlainText -Force $Credential = New-Object
-TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
#Define the list of AAS databases
$asDBs = #('database1','database2')
Write-Output "Logging in to Azure..."
#Add-AzureAnalysisServicesAccount -Credential $Credential -ServicePrincipal -TenantId $TenantId -RolloutEnvironment $RolloutEnvironment
ForEach($db in $asDBs)
{
Write-Output "Starting Backup..."
Backup-ASDatabase `
–backupfile ($db +"." + (Get-Date).ToString("ddMMyyyy") + ".abf") `
–name $db `
-server $Server `
-Credential $Cred
Write-Output "Backup Completed!"
}
You are correct that the issue is with multi-factor authentication. Since the point of multi-factor is the require interaction with a secondary source like your phone there is no way to automate the process.
I would suggest that you look into using service principle authentication for the purpose of taking backups. By using a service principle to your server you can allow for automated tasks to run without 2-factor while minimizing the security risk.

Azure Runbook Commands

So I have a runbook which automates the shutdown and start-up of my Azure VM during the weekends. This then sends a transactional email confirming that the VPS is shut down/started up.
I have set up my parameters as illustrated. Is there a reason as to why it correctly states the name of my virtual machine (highlighted) in the subject line but in the body of the email (highlighted), it comes up with a completely different name.
Logic would dictate that $VM.NAME would be the name of the VPS and not some random command line, so why is this? It's displayed correctly in the subject line but not the email body.
param (
[Parameter(Mandatory=$false)]
[String] $VMName ="ITAMTRADINGVPS",
[Parameter(Mandatory=$false)]
[String] $ResourceGroupName
)
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
# If there is a specific resource group, then get all VMs in the resource group,
# otherwise get all VMs in the subscription.
if ($ResourceGroupName -And $VMName)
{
$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName -Name $VMName
}
elseif ($ResourceGroupName)
{
$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName
}
else
{
$VMs = Get-AzureRmVM
}
$vms
# Start each of the VMs
# Stop each of the VMs
foreach ($VM in $VMs)
{
$StopRtn = $VM | Stop-AzureRmVM -Force -ErrorAction Continue
$StopRtn
Write-Output " this is $StopRtn "
if ($StopRtn.IsSuccessStatusCode -eq 'True')
{
# The VM stopped, so send notice
Write-Output ($VM.Name + " has been stopped")
$Username ="xxx"
$Password = ConvertTo-SecureString "xxx" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $Username, $Password
$SMTPServer = "xxx"
$EmailFrom = "xxxx
[string[]]$EmailTo = "xxx"
$Subject = $VM.NAME + " notification of scheduled deallocation"
$Body = "We'd like to let you know that your Virtual Machine $VM.NAME has successfully deallocated.
<br>This could either be due to maintenance or a scheduled shutdown. If you were expecting this notification, please disregard this email.
<br><br>If you need any further assistance, please contact the system administrator on xxx<br><br>Yours Sincerely<br><br>The Technical Design Team<br>xxx<br><br>"
Send-MailMessage -smtpServer $SMTPServer -Credential $credential -Usessl -Port 587 -from $EmailFrom -to $EmailTo -subject $Subject -Body $Body -BodyAsHtml
Write-Output "Email sent succesfully."
}
else
{
# The VM failed to stop, so send notice
Write-Output ($VM.Name + " failed to stop")
}
}
Illustration
The variable reference (e.g. $VM.Name) into the email body which by default will just return the object type where the output in PowerShell is a special pipeline activity which will render the content either as a listing or as a table. In order to include content in an email, we would have to reference the properties
[string]$EmailBody = (“VMNAME IS = [{0}]” -f $VM.Name)
which is similar to string.format in C#
Refer this SO

How to use PowerShell parameter in Jenkins

I am using PowerShell to automate VM start/stop in Azure. However, when I set the $OPTION parameter it doesn't do anything. I have if/elseif/else statements.
See code below:
Add-AzureRmAccount -Credential $psCred -TenantId <removed> -ServicePrincipal
Get-AzureRmSubscription -SubscriptionName "<removed>"
#Get VMs using Tags
$vms = (Find-AzureRmResource | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName)
$vms
Write-Output "Number of Virtual Machines: $($vms.Name.Count)"
foreach($VM in $vms)
{
if ($OPTION -eq "start" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines")
{
Write-Output "Starting :- $VM.Name in $VM.ResourceGroupName"
Start-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Verbose
Write-Output $VM.Name "has started successfully"
Write-Output "Writing output to workspace"
Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Start_Info-$(get-date -f yyyy-MM-dd).tsv
}
elseif ($OPTION -eq "stop" -And $VM.ResourceType -eq "Microsoft.Compute/virtualMachines")
{
Write-Output "Deallocating :- $VM.Name in $VM.ResourceGroupName"
Stop-AzureRmVM -ResourceGroupName $VM.ResourceGroupName -Name $VM.Name -Force -Verbose
Write-Output $VM.Name "has been deallocated successfully"
Write-Output "Writing output to workspace"
Get-AzureRmVM -Status | Where-Object {($_.tags.Project -eq "DevOps") -And ($_.tags.Test -eq "ernest")} | Select Name, ResourceGroupName, PowerState > VM_Stopped_Info-$(get-date -f yyyy-MM-dd).tsv
}
else
{
Write-Output "No option selected, select an option"
}
}
Write-Output "Script complete"
I had to add the $env:OPTION parameter to the Execute Powershell window. It works now

Resources