development

Windows 서비스가 존재하는지 확인하고 PowerShell에서 삭제

big-blog 2020. 6. 22. 07:19
반응형

Windows 서비스가 존재하는지 확인하고 PowerShell에서 삭제


현재 많은 Windows 서비스를 설치하는 배포 스크립트를 작성 중입니다.

서비스 이름은 버전이 지정되어 있으므로 새 서비스 설치의 일부로 이전 Windows 서비스 버전을 삭제하고 싶습니다.

PowerShell에서 가장 잘 수행 할 수있는 방법은 무엇입니까?


Remove-ServicePowershell 6.0까지 cmdlet 이 없으므로 WMI 또는 기타 도구를 사용할 수 있습니다 ( Remove-Service 문서 참조).

예를 들면 다음과 같습니다.

$service = Get-WmiObject -Class Win32_Service -Filter "Name='servicename'"
$service.delete()

또는 sc.exe도구를 사용하여 :

sc.exe delete ServiceName

마지막으로 PowerShell 6.0에 액세스 할 수있는 경우 :

Remove-Service -Name ServiceName

작업에 적합한 도구를 사용하는 데 아무런 해가 없습니다 .Powershell에서 실행 중입니다.

sc.exe \\server delete "MyService" 

많은 의존성이없는 가장 신뢰할 수있는 방법.


서비스 존재 여부 만 확인하려는 경우 :

if (Get-Service "My Service" -ErrorAction SilentlyContinue)
{
    "service exists"
}

"-ErrorAction SilentlyContinue"솔루션을 사용했지만 나중에 ErrorRecord가 남는 문제가 발생했습니다. "Get-Service"를 사용하여 서비스가 있는지 확인하는 또 다른 솔루션이 있습니다.

# 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 

그러나 서비스가 존재하지 않으면 Get-WmiObject에서 오류가 발생하지 않으므로 ravikanth가 최상의 솔루션을 제공합니다. 그래서 나는 다음을 사용하여 정착했습니다.

Function ServiceExists([string] $ServiceName) {
    [bool] $Return = $False
    if ( Get-WmiObject -Class Win32_Service -Filter "Name='$ServiceName'" ) {
        $Return = $True
    }
    Return $Return
}

보다 완벽한 솔루션을 제공하려면 다음을 수행하십시오.

# 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
}

최신 버전의 PS에는 Remove-WmiObject가 있습니다. $ service.delete ()에 대해 자동 실패에주의하십시오 ...

PS D:\> $s3=Get-WmiObject -Class Win32_Service -Filter "Name='TSATSvrSvc03'"

PS D:\> $s3.delete()
...
ReturnValue      : 2
...
PS D:\> $?
True
PS D:\> $LASTEXITCODE
0
PS D:\> $result=$s3.delete()

PS D:\> $result.ReturnValue
2

PS D:\> Remove-WmiObject -InputObject $s3
Remove-WmiObject : Access denied 
At line:1 char:1
+ Remove-WmiObject -InputObject $s3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Remove-WmiObject], ManagementException
    + FullyQualifiedErrorId : RemoveWMIManagementException,Microsoft.PowerShell.Commands.RemoveWmiObject

PS D:\> 

내 상황에서는 '관리자 권한으로'를 실행해야했습니다.


이 버전에는 서비스 제거가 없으므로 Powershell 5.0에서 여러 서비스를 삭제하려면

아래 명령을 실행하십시오

Get-Service -Displayname "*ServiceName*" | ForEach-object{ cmd /c  sc delete $_.Name}

Dmitri와 dcx의 답변을 결합하여 다음과 같이했습니다.

function Confirm-WindowsServiceExists($name)
{   
    if (Get-Service $name -ErrorAction SilentlyContinue)
    {
        return $true
    }
    return $false
}

function Remove-WindowsServiceIfItExists($name)
{   
    $exists = Confirm-WindowsServiceExists $name
    if ($exists)
    {    
        sc.exe \\server delete $name
    }       
}

Where-Object를 사용할 수 있습니다

if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) { "Service Exists" }


To check if a Windows service named MySuperServiceVersion1 exists, even when you might not be sure of its exact name, you could employ a wildcard, using a substring like so:

 if (Get-Service -Name "*SuperService*" -ErrorAction SilentlyContinue)
{
    # do something
}

For single PC:

if (Get-Service "service_name" -ErrorAction 'SilentlyContinue'){(Get-WmiObject -Class Win32_Service -filter "Name='service_name'").delete()}

else{write-host "No service found."}

Macro for list of PCs:

$name = "service_name"

$list = get-content list.txt

foreach ($server in $list) {

if (Get-Service "service_name" -computername $server -ErrorAction 'SilentlyContinue'){
(Get-WmiObject -Class Win32_Service -filter "Name='service_name'" -ComputerName $server).delete()}

else{write-host "No service $name found on $server."}

}

PowerShell Core (v6+) now has a Remove-Service cmdlet.

I don't know about plans to back-port it to Windows PowerShell, where it is not available as of v5.1.

Example:

# PowerShell *Core* only (v6+)
Remove-Service someservice

Note that invocation fails if the service doesn't exist, so to only remove it if it currently exists, you could do:

# PowerShell *Core* only (v6+)
$name = 'someservice'
if (Get-Service $name -ErrorAction Ignore) {
  Remove-Service $name
}

Adapted this to take an input list of servers, specify a hostname and give some helpful output

            $name = "<ServiceName>"
            $servers = Get-content servers.txt

            function Confirm-WindowsServiceExists($name)
            {   
                if (Get-Service -Name $name -Computername $server -ErrorAction Continue)
                {
                    Write-Host "$name Exists on $server"
                    return $true
                }
                    Write-Host "$name does not exist on $server"
                    return $false
            }

            function Remove-WindowsServiceIfItExists($name)
            {   
                $exists = Confirm-WindowsServiceExists $name
                if ($exists)
                {    
                    Write-host "Removing Service $name from $server"
                    sc.exe \\$server delete $name
                }       
            }

            ForEach ($server in $servers) {Remove-WindowsServiceIfItExists($name)}

  • For PowerShell versions prior to v6, you can do this:

    Stop-Service 'YourServiceName'; Get-CimInstance -ClassName Win32_Service -Filter "Name='YourServiceName'" | Remove-CimInstance
    
  • For v6+, you can use the Remove-Service cmdlet.

Windows PowerShell 3.0부터 Get-WmiObject cmdlet 이 Get-CimInstance로 대체되었습니다.


Windows Powershell 6에는 Remove-Service cmdlet이 있습니다. 현재 Github 릴리스는 PS v6 베타 -9를 보여줍니다.

출처 : https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/remove-service?view=powershell-6

참고 URL : https://stackoverflow.com/questions/4967496/check-if-a-windows-service-exists-and-delete-in-powershell

반응형