I need to stop and then remove a Windows Service and the following PowerShell commands work successfully:
Get-Service "$ServiceName" | Stop-Service
Get-Service "$ServiceName" | Remove-Service
I think it's possible to combine this into a single line of code, but in my PowerShell research the multiple piping to pass commandlet values to the next operation, or the use of a semicolon didn't work:
Get-Service "$ServiceName" | Stop-Service | Remove-Service # Does not work
Get-Service "$ServiceName" | Stop-Service; Remove-Service # Does not work
Is there a way to combine these statements into a single line, or at least use the value of Get-Service
to perform those operations without having to call it 2x?
Stop-Service
is one of those cmdlets that consumes the object. So, you'd have to supply it the -PassThru
switch to allow the object to continue down the pipeline:
Get-Service "$ServiceName" |
Stop-Service -PassThru |
Remove-Service
As for your last example, the semicolon (;
) is a means of statement termination in PowerShell, so you're essentially executing 2 commands where Remove-Service
doesn't have anything to reference.