为什么在函数中的return语句之后打印Write-Host消息?

时间:2018-09-18 16:20:01

标签: powershell

我编写了以下函数来尝试启动当前未运行的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正在运行

1 个答案:

答案 0 :(得分:5)

这是因为 $AgentServiceName 是一个字符串。您需要检查的是 $agentService

$agentService = Get-Service -Name $AgentServiceName

if ($agentService.Status -eq "Running")
{
    Write-Host "$AgentServiceName is running"
    return
}

Write-Host "Starting $AgentServiceName..."