Powershell Script Get-Hyper-V and Send-Emailmessage

Daniel Bove 81 Reputation points
2020-10-23T23:03:16.617+00:00

Maybe i am going about this the wrong way. I want to run the get-hyper-v command then email it. I will schedule a task to run it.

I can get this to work but not consistently. It prompts for credentials, then I will hit cancel. Run the script again, and then it works.

$status = Get-VMReplication | Select-Object Name, State, Health, Mode, FrequencySec, PrimaryServer, ReplicaServer, ReplicaPort | ConvertTo-Html

Send-MailMessage -To ******@mydomain.org -from ******@mydomain.org -Subject 'Hyper-V Replication Status' -Body "$status" -BodyAsHtml -smtpserver smtp.office365.com -usessl -Port 587 -Credential $Credential

$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$User = "******@mydomain.org"
$PWord = Get-Content "C:\temp\hyper-v.zip" | ConvertTo-SecureString -Force
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Anonymous
2020-10-26T03:36:43.56+00:00

Hi,

You should define a variable before using it otherwise the variable is null.

$status = Get-VMReplication | Select-Object Name, State, Health, Mode, FrequencySec, PrimaryServer, ReplicaServer, ReplicaPort | ConvertTo-Html  
$User = "******@mydomain.org"  
$PWord = Get-Content "C:\temp\hyper-v.zip" | ConvertTo-SecureString -Force  
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord      
Send-MailMessage -To ******@mydomain.org -from ******@mydomain.org -Subject 'Hyper-V Replication Status' -Body "$status" -BodyAsHtml -smtpserver smtp.office365.com -usessl -Port 587 -Credential $Credential  

Best Regards,
Ian

============================================

If the Answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?


2 additional answers

Sort by: Most helpful
  1. Leo Visser 326 Reputation points MVP
    2020-10-24T14:51:56.51+00:00

    You are defining the credential variable after you are using it. Move line 3 to the bottom of the script and it should work.

    Was this answer helpful?


  2. Rich Matheisen 48,116 Reputation points
    2020-10-24T01:51:52.603+00:00

    Have you tried moving line #5 to the bottom of the script? Also move line #3 so follows the relocated line #5. Or, just move lines 5, 6, an 7 to the top of the script and rearrange them so the variables are loaded before they're used.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.