我编写了以下函数来尝试启动当前未运行的 Sql Server 代理服务:
function Start-SqlAgent([string] $AgentServiceName)
{
$agentService = Get-Service -Name $AgentServiceName
if ($AgentServiceName.Status -eq "Running")
{
Write-Host "$AgentServiceName is running"
return
}
Write-Host "Starting $AgentServiceName..."
# Code that starts the service below here (unrelated to my question)
}
当 Sql 代理服务运行时,我像这样调用函数:
Write-Host "Checking SQL Agent service status..."
Start-SqlAgent -AgentServiceName "SQLSERVERAGENT"
我得到以下输出:
正在检查 SQL 代理服务状态...
正在启动 SQLSERVERAGENT...
为什么显示Starting SQLSERVERAGENT...
消息?我期望的输出是:
正在检查 SQL 代理服务状态...
SQLSERVER代理正在运行
那是因为$AgentServiceName
是一个字符串。您需要检查的是$agentService
.
$agentService = Get-Service -Name $AgentServiceName
if ($agentService.Status -eq "Running")
{
Write-Host "$AgentServiceName is running"
return
}
Write-Host "Starting $AgentServiceName..."