使用 PowerShell 验证 Windows 服务是否未运行并发送包含信息的电子邮件

问题描述 投票:0回答:1

我已经创建了这个 powershell 代码。 它运行并发送一封电子邮件,其中包含每台远程计算机、服务以及似乎的状态的详细信息。

但是,服务名称和状态似乎无法正常运行。该脚本的输出告诉我找不到该服务。但是,我通过在运行完整脚本的同一台计算机上运行它来验证服务是否存在并识别实际服务的状态来检查这一点;

Get-Service -ComputerName machine1 -Name MyService

我的完整 PowerShell 脚本如下;

# Define the list of machine names where the service should be checked
$machineNames = @("machine1","machine2")  # Add more machine names as needed

# Define the service name to check
$serviceName = "MyService"

# Function to check service status on a specific machine
function Get-ServiceStatus {
param (
    [string]$machineName,
    [string]$service
)

$serviceStatus = Get-Service -ComputerName $machineName -Name $service -ErrorAction 
SilentlyContinue
if ($serviceStatus) {
    return $serviceStatus.Status
} else {
    return "Service Not Found"
}
}

# Initialize an empty array to store information about services that are not running
$notRunningServices = @()

# Check the service status on each machine
foreach ($machine in $machineNames) {
$status = Get-ServiceStatus -machineName $machine -service $serviceName
if ($status -ne "Running") {
    $notRunningServices += [PSCustomObject]@{
        MachineName = $machine
        ServiceName = $serviceName
        Status = $status
    }
}
}

# If there are services not running, send an email
if ($notRunningServices.Count -gt 0) {
$smtpServer = "smtp.server.com"
$smtpPort = 25
$fromAddress = "[email protected]"  
$toAddress = "[email protected]"

$emailSubject = "MyService Service Status - Not Running"
$emailBody = "The following services are not running:`r`n`r`n"

foreach ($service in $notRunningServices) {
    $emailBody += "Server: $($service.MachineName)`r`nService: 
$($service.ServiceName)`r`nStatus: $($service.Status)`r`n`r`n"
}

Send-MailMessage -From $fromAddress -To $toAddress -Subject $emailSubject -Body $emailBody - 
SmtpServer $smtpServer -Port $smtpPort
}

我需要解析 powershell 脚本来识别每台计算机上的远程服务名称。

电子邮件副本在这里;

以下服务未运行:

服务器:机器1 服务:我的服务 状态:未找到服务

服务器:机器2 服务:我的服务 状态:未找到服务

如果有人能提供帮助,我将不胜感激。

提前致谢

powershell server service sendmail
1个回答
0
投票

我测试了你的脚本,它可以在我的测试环境中运行。

检查 ActiveDirectoryWebService (ADWS) 的成员服务器 (TESTSRV) 和 DC (TESTDC) 的结果:

$notRunningServices    

MachineName ServiceName Status           
----------- ----------- ------           
TESTSRV     ADWS        Service Not Found

我假设您正在将其作为计划任务运行。

也许是权限问题?

邮件正文提示:使用“HERE-String”

示例:

$emailBody = @"
The following services are not running:
$notRunningServices
"@

如果您需要在正文中使用特殊字符,只需将 -Encoding OEM 添加到 Send-MailMessage 命令即可。

© www.soinside.com 2019 - 2024. All rights reserved.