gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:33:29 27 4
gpt4 key购买 nike

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

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

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

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

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

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

谢谢!

最佳答案

我不确定 sc start 之间的区别和 start-service ,但您可以使用 wmi 来做您想做的事。

启动服务:

(get-wmiobject win32_service -filter "name='the service'").startService()

停止服务:
(get-wmiobject win32_service -filter "name='the service'").stopService()

要检查服务的状态,您可以使用:
get-wmiobject win32_service -filter "name='the service'"

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

停止服务:
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

启动服务:
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

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

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

关于service - PowerShell 2 中 sc start ... 和 Start-Service ... 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12332327/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com