PowerShell 2 中 sc start ... 和 Start-Service ... 之间的区别

Bre*_*ett 4 service windows-server-2003 powershell-2.0

我在同一台机器上安装了几个不同的服务。我正在编写一个 PowerShell 2 脚本来启动和停止它们。

对于某些服务,我可以使用Start-Service -displayname "the service"它来成功启动它。在其他情况下,使用Start-Servicecmdlet 会导致“无法在计算机上启动服务...'.'”的原因和错误。

在我使用Start-Servicecmdlet出现错误的情况下,sc start "the service"总是成功。

反之亦然(虽然sc start不返回任何错误——它只是根本不启动服务。)

这些命令之间有什么区别吗?是否有我应该使用的替代命令?最后,我可以从 cmdlet 中“捕获”任何错误,并且只包含两个命令以涵盖所有基础吗?

这个问题对我来说是可重复的,即使我卸载并重新安装服务。

谢谢!

Nic*_*ick 5

我不知道之间的差异sc startstart-service,但你可以使用WMI做你想做的。

启动服务:

(get-wmiobject win32_service -filter "name='the service'").startService()
Run Code Online (Sandbox Code Playgroud)

停止服务:

(get-wmiobject win32_service -filter "name='the service'").stopService()
Run Code Online (Sandbox Code Playgroud)

要检查服务的状态,您可以使用:

get-wmiobject win32_service -filter "name='the service'"
Run Code Online (Sandbox Code Playgroud)

它将显示状态和启动模式。如果要自动执行此操作,可以使用以下内容。

停止服务:

if ((get-wmiobject win32_service -filter "name='the service'").state -eq "Running") {
    (get-wmiobject win32_service -filter "name='the service'").stopService()
} # Stops the service if it is running
Run Code Online (Sandbox Code Playgroud)

启动服务:

if ((get-wmiobject win32_service -filter "name='the service'").state -eq "Stopped") {
    (get-wmiobject win32_service -filter "name='the service'").startService()
} # starts the service if it is stopped
Run Code Online (Sandbox Code Playgroud)

我相信你可以修改它们以满足你的需要。

我喜欢使用 wmi 的原因是能够指定-computername-credentials. 它使您可以访问远程系统并在您拥有非域系统时对其进行身份验证。希望有所帮助。祝你有美好的一天!