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

Powershell 为什么在函数中的return语句之后打印Write Host消息?,powershell,Powershell,我编写了以下函数,试图在Sql Server代理服务当前未运行时启动该服务: function Start-SqlAgent([string] $AgentServiceName) { $agentService = Get-Service -Name $AgentServiceName if ($AgentServiceName.Status -eq "Running") { Write-Host "$AgentServi

我编写了以下函数,试图在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

为什么会显示
启动SQLSERVERAGENT…
消息?我预期的结果是:

正在检查SQL代理服务状态

SQLSERVERAGENT正在运行


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

$agentService = Get-Service -Name $AgentServiceName

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

Write-Host "Starting $AgentServiceName..."

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

$agentService = Get-Service -Name $AgentServiceName

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

Write-Host "Starting $AgentServiceName..."

显然,您的
if
语句失败了。根据你的问题,我们只能肯定地告诉你这些。确保servicename实际上是
sqlserveragent
,并且您没有实际引用displayname。显然,您的
if
语句失败了。根据你的问题,我们只能肯定地告诉你这些。确保servicename实际上是
sqlserveragent
,并且您没有实际引用displayname。该死的,我是笨蛋。我知道这很简单,但我没有看到。非常感谢。“当答案允许我的时候,我会接受的。”刘塞林说。应该为引用的、未定义的变量编写PSSA规则!FWIW,一个像Visual Studio Code这样的高级编辑器将告诉您,$agentService未使用。这是我现在唯一一个用在PowerShell上的编辑器。天哪,我是个笨蛋。我知道这很简单,但我没有看到。非常感谢。“当答案允许我的时候,我会接受的。”刘塞林说。应该为引用的、未定义的变量编写PSSA规则!FWIW,一个像Visual Studio Code这样的高级编辑器将告诉您,$agentService未使用。这是我现在唯一使用的PowerShell编辑器。