Tôi đã sử dụng giải pháp "-ErrorAction SilentlyContinue" nhưng sau đó gặp phải vấn đề là nó để lại ErrorRecord. Vì vậy, đây là một giải pháp khác để kiểm tra xem Dịch vụ có tồn tại bằng cách sử dụng "Dịch vụ nhận" hay không.
# Determines if a Service exists with a name as defined in $ServiceName.
# Returns a boolean $True or $False.
Function ServiceExists([string] $ServiceName) {
[bool] $Return = $False
# If you use just "Get-Service $ServiceName", it will return an error if
# the service didn't exist. Trick Get-Service to return an array of
# Services, but only if the name exactly matches the $ServiceName.
# This way you can test if the array is emply.
if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
$Return = $True
}
Return $Return
}
[bool] $thisServiceExists = ServiceExists "A Service Name"
$thisServiceExists
Nhưng rastaanth có giải pháp tốt nhất vì Get-WmiObject sẽ không gây ra lỗi nếu Dịch vụ không tồn tại. Vì vậy, tôi quyết định sử dụng:
Function ServiceExists([string] $ServiceName) {
[bool] $Return = $False
if ( Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" ) {
$Return = $True
}
Return $Return
}
Vì vậy, để cung cấp một giải pháp đầy đủ hơn:
# Deletes a Service with a name as defined in $ServiceName.
# Returns a boolean $True or $False. $True if the Service didn't exist or was
# successfully deleted after execution.
Function DeleteService([string] $ServiceName) {
[bool] $Return = $False
$Service = Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'"
if ( $Service ) {
$Service.Delete()
if ( -Not ( ServiceExists $ServiceName ) ) {
$Return = $True
}
} else {
$Return = $True
}
Return $Return
}