我编写了以下函数来尝试启动当前未运行的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 Agent服务正在运行时,我这样调用该函数:
Write-Host "Checking SQL Agent service status..."
Start-SqlAgent -AgentServiceName "SQLSERVERAGENT"
我得到以下输出:
正在检查SQL Agent服务状态...
正在启动SQLSERVERAGENT ...
为什么显示Starting SQLSERVERAGENT...
消息?我期望的输出是:
正在检查SQL Agent服务状态...
SQLSERVERAGENT正在运行
答案 0 :(得分:5)
这是因为 $AgentServiceName
是一个字符串。您需要检查的是 $agentService
。
$agentService = Get-Service -Name $AgentServiceName
if ($agentService.Status -eq "Running")
{
Write-Host "$AgentServiceName is running"
return
}
Write-Host "Starting $AgentServiceName..."