How to add my script to one variable

Hi,

I started a script that will restart a service for me on one of our servers periodically, however I’d like the output of this script to be emailed to other administrators as well as our manager so we can see that it was executed and what it did exactly. From what I’ve gathered in my research I need to turn my script in to a varieable so that I can use that veriable with the send-mailmessage command to go in to the body of my email. I’m definately a novice at best.

Simplified question is how can I put this script in to one variable that I can reference in an email send command?

$srvName = “Microsoft Monitoring Agent”
$servicePrior = Get-Service $srvName
"$srvName is now " + $servicePrior.status
Stop-Service $srvName
start-sleep -s 120
Start-Service $srvName
start-sleep -s 120
$serviceAfter = Get-Service $srvName
"$srvName is now " + $serviceAfter.status

Any help is greatly appreciated.

To add this will be the mail part of the script that I hope to get working in conjunction with the above.

$email = @{
From = “email@email.com
To = “email@email.com
Subject = “Powershell Test”
SMTPServer = “smtp.*******.com”
Body = $body
}

send-mailmessage @email

Hello, Michael. Well, you can put your code in a function. Like this:

function Restart-MyService {
    $srvName = "Microsoft Monitoring Agent"
    $servicePrior = Get-Service $srvName
    "$srvName is now " + $servicePrior.status
    Stop-Service $srvName
    start-sleep -s 120
    Start-Service $srvName
    start-sleep -s 120
    $serviceAfter = Get-Service $srvName
    "$srvName is now " + $serviceAfter.status
}

$body = Restart-MyService | Out-String

$email = @{
From = "email@email.com"
To = "email@email.com"
Subject = "Powershell Test"
SMTPServer = "smtp.*******.com"
Body = $body
}

send-mailmessage @email

I don’t have a local SMTP server, though, so I can’t check if it works properly.

UPD: Fixed the code to properly handle multiline output.

HUGE, thank you!

It worked, not exactly how I planned but it at least tells us that the service has been restarted which is a big help. Next I need to figure out how to add the logic to restart the service again if it fails to start.

VERY appreciated, thank you!