如何将多个Windows Service PowerShell命令组合成一个语句?

问题描述 投票:0回答:1

我需要停止然后删除 Windows 服务,并且以下 PowerShell 命令可以成功运行:

Get-Service "$ServiceName" | Stop-Service 
Get-Service "$ServiceName" | Remove-Service

认为可以将其合并到一行代码中,但在我的PowerShell研究中,使用多个管道将命令行开关值传递给下一个操作,或者使用分号不起作用:

Get-Service "$ServiceName" | Stop-Service | Remove-Service  # Does not work
Get-Service "$ServiceName" | Stop-Service; Remove-Service # Does not work

有没有办法将这些语句组合成一行,或者至少使用

Get-Service
的值来执行这些操作,而不必调用它 2x?

powershell windows-services
1个回答
1
投票

Stop-Service
是使用该对象的 cmdlet 之一。因此,您必须为其提供
-PassThru
开关以允许对象继续沿着管道运行:

Get-Service "$ServiceName" | 
    Stop-Service -PassThru | 
    Remove-Service

对于最后一个示例,分号 (

;
) 是 PowerShell 中语句终止的一种方法,因此您实际上是在执行 2 个命令,其中
Remove-Service
没有任何可引用的内容。

© www.soinside.com 2019 - 2024. All rights reserved.