系统学习 Windows 学习路径:从 CMD 到 PowerShell、系统网络,再到 WSL 与 Server

Stop-Service

停止 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

易错点与排错

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. Stop-Service -Force 的“Force”具体多做了什么?风险是什么?
  2. -NoWait 之后马上启动同一服务,可能遇到什么问题?
  3. 服务停止后自动又起来,应该检查什么配置?
答案
  1. 会停止该服务及其依赖服务;风险是连带中断依赖它的业务或用户会话。
  2. 服务可能还在 StopPending,启动会失败;需要轮询状态或使用默认等待。
  3. 用 sc.exe qfailure <服务名> 查看失败恢复策略,确认是否被自动重启,以及是否有监控/守护程序。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令