停止 Windows 服务;-Force 会连带停止依赖服务。
Stop-Service 按服务名或 ServiceController 对象停止服务,默认等待服务进入 Stopped 后返回,-NoWait 可立即返回;默认不输出结果,-PassThru 返回服务对象,支持 -WhatIf,别名是 spsv。停止请求由 SCM 执行,服务有机会运行自己的 OnStop 逻辑,但不保证业务数据已落盘。
管道:接受 ServiceController 对象按值输入,也接受 Name 按属性名绑定;Get-Service ... | Stop-Service 是常见写法。权限:通常需要管理员或服务安全描述符授予的停止权限。-Force 会停止依赖该服务的其他服务,可能中断用户会话或业务链路,执行前先用 -DependentServices 看清范围。
边界:服务卡死、不响应停止请求时,Stop-Service 可能超时,最终要定位宿主进程;不要用 Stop-Process 代替常规服务停止。版本:5.1 与 7.x 都仅限 Windows,7.x 在非 Windows 平台没有该命令。
# 1. 预览停止操作,确认服务名和当前状态
PS C:\> Stop-Service -Name Spooler -WhatIf
# 2. 停止并返回对象,确认最终状态
PS C:\> Stop-Service -Name Spooler -PassThru | Select-Object Name, Status
# 3. 有依赖服务时先预览 -Force 的连带影响
PS C:\> Get-Service -Name LanmanServer -DependentServices | Select-Object Name, Status
PS C:\> Stop-Service -Name LanmanServer -Force -WhatIf
# 4. 不等待停止完成,适合并行脚本,随后自行轮询
PS C:\> Stop-Service -Name W32Time -NoWait; Start-Sleep 2; Get-Service W32Time
# 5. 捕获服务名错误,避免脚本继续执行后续危险步骤
PS C:\> try { Stop-Service -Name 'NotExist' -ErrorAction Stop } catch { $_.Exception.Message }
# 6. 批量停止测试环境中的运行中服务
PS C:\> Get-Service | Where-Object { $_.DisplayName -like 'Test*' -and $_.Status -eq 'Running' } | Stop-Service -PassThru
-Force 时会报“无法停止,因为有依赖服务”;-Force 会把这些依赖服务一起停掉。先 -DependentServices 确认影响范围,再决定。-NoWait 返回时服务可能仍是 StopPending,紧接着启动会失败;需要立即操作时轮询 Status 或改用默认等待。sc.exe qfailure <服务名> 查看恢复动作,必要时先调整策略。Automatic 不会因为一次停止而改变;要防止下次开机自启,需要管理员修改启动类型。Stop-Service;跨平台脚本先判断 $IsWindows。Get-Service — 查状态、依赖和启动类型。Start-Service — 重新启动或按依赖顺序拉起服务。sc — 查询服务配置、失败恢复和删除服务。Stop-Process — 仅在服务卡死且明确知道宿主进程时使用。合上页面,先回答,再展开对照。
Stop-Service -Force 的“Force”具体多做了什么?风险是什么?-NoWait 之后马上启动同一服务,可能遇到什么问题?StopPending,启动会失败;需要轮询状态或使用默认等待。sc.exe qfailure <服务名> 查看失败恢复策略,确认是否被自动重启,以及是否有监控/守护程序。
小程序版
微信扫码,随时查命令