programing

Powershell을 사용하여 WMI 또는 원격 없이 원격으로 서비스 중지

subpage 2023. 9. 11. 21:50
반응형

Powershell을 사용하여 WMI 또는 원격 없이 원격으로 서비스 중지

작동하는 것처럼 보이는 라이너 하나를 우연히 발견했습니다.

stop-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

원격 서비스를 사용하거나 로컬 호스트에서 발생하지 않는 한 중지 서비스가 작동하지 않는다고 생각했기 때문에 그 이유를 설명할 수 있는 사람이 있습니까?

산출량Get-ServiceSystem.ServiceProcess.ServiceController원격 시스템에서 작동할 수 있는 .NET 클래스.그것이 어떻게 이루어지는지는 모르겠습니다. 아마도 DCOM이나 WMI일 것입니다. 이것들 중 하나를 얻으시면 됩니다.Get-Service, 에 전달될 수 있습니다.Stop-Service아마도 단지 그들을 그들이라고 부를 것입니다.Stop()이 개체의 메서드입니다.그러면 원격 컴퓨터에서 서비스가 중지됩니다.실제로 이 작업을 수행할 수도 있습니다.

(get-service -ComputerName remotePC -Name Spooler).Stop()

이 질문에 많은 분들이 보내주신 덕분에 다음과 같은 대본을 생각해 냈습니다.값 변경$SvcName그리고.$SvrName당신의 필요에 맞게.원격 서비스가 중지되면 이 스크립트가 원격 서비스를 시작하거나 시작되면 원격 서비스를 중지합니다.그리고 시원한 것을 사용합니다..WaitForStatus서비스가 응답하는 동안 대기할 메서드입니다.

#Change this values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'remotePC'

#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
    'Stopped' {
        Write-host "Starting $SvcName..."
        $Verb = "start"
        $WaitForIt = 'Running'
        $svc.Start()}
    'Running' {
        Write-host "Stopping $SvcName..."
        $Verb = "stop"
        $WaitForIt = 'Stopped'
        $svc.Stop()}
    Default {
        Write-host "$SvcName is $($svc.status).  Taking no action."}
}
if ($WaitForIt -ne "") {
    Try {  # For some reason, we cannot use -ErrorAction after the next statement:
        $svc.WaitForStatus($WaitForIt,'00:02:00')
    } Catch {
        Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
    }
    $svc = (get-service -computername $SvrName -name $SvcName)
    if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
    Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}

물론 아래에서 이 계정을 실행하는 계정은 원격 컴퓨터에 액세스하고 서비스를 시작 및 중지하는 데 적절한 권한이 필요합니다.그리고 이전 원격 시스템에 대해 이 작업을 실행할 때는 먼저 이전 시스템에 WinRM 3.0을 설치해야 할 수도 있습니다.

내장된 파워셸 예를 바탕으로 마이크로소프트가 제안하는 내용입니다.테스트 및 검증:

중지하려면:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StopService()

시작 방법:

(Get-WmiObject Win32_Service -filter "name='IPEventWatcher'" -ComputerName Server01).StartService()

이것은 나에게 효과가 있었지만, 나는 이것을 시작으로 사용했습니다. 파워셸 출력, 서비스가 시작되기를 몇 번 기다렸다가 끝나면 원격 서버에서 서비스가 시작된 것으로 표시됩니다.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

다른 옵션; 사용invoke-command:

cls
$cred = Get-Credential
$server = 'MyRemoteComputer'
$service = 'My Service Name' 

invoke-command -Credential $cred -ComputerName $server -ScriptBlock {
    param(
       [Parameter(Mandatory=$True,Position=0)]
       [string]$service
    )
    stop-service $service 
} -ArgumentList $service

NB: 이 옵션을 사용하려면 원격 컴퓨터에 PowerShell을 설치해야 하고 방화벽에서 요청을 통과할 수 있도록 해야 하며, Windows 원격 관리 서비스가 대상 컴퓨터에서 실행되도록 해야 합니다.대상 시스템에서 직접 다음 스크립트를 실행하여 방화벽을 구성할 수 있습니다(단 한 번의 작업).Enable-PSRemoting -force.

할 수도 있습니다.(Get-Service -Name "what ever" - ComputerName RemoteHost).Status = "Stopped"

각 항목에 대해 실행하고 로깅을 활성화할 수 있습니다.콘솔에 문제가 있는지 표시되며 로그를 확인할 수 있습니다.

그러면 오류를 개별적으로 처리할 수 있습니다.

방화벽 규칙이 값 false를 생성할 수 있기 때문에 검증 부분에 대한 Test-Net 연결을 실행하는 것보다 이 방법이 더 효과적이라고 생각합니다.

이 예에서는 서버 이름 열이 있는 csv 파일을 servername.contoso.com 으로 채웁니다.

$ServerList = "$PSScriptRoot\Serverlist.csv"

$Transcriptlog = "$PSScriptRoot\Transcipt.txt"
    
    Start-Transcript -Path $Transcriptlog -Force
    Get-Date -Format "yyyy/MM/dd HH:mm" 
    
    Try 
     { # Start Try  
       $ImportServerList = Import-Csv $ServerList -Encoding UTF8 | ForEach-Object { # Start Foreach 
        New-Object PsObject -Prop @{ # Start New-Object 
         ServerName = $_.ServerName } # End NewObject 
          Invoke-Command -ComputerName $_.ServerName -ErrorAction Continue -ScriptBlock  { # Start ScriptBlock  
           # Disable Service PrintSpooler
           Get-Service -Name Spooler | Stop-Service -Force 
    
       } # End ScriptBlock
      } # End Foreach       
     } # End Try
    
    Catch
     { # Start Catch 
      Write-Warning -Message "## ERROR## " 
      Write-Warning -Message "## Script could not start ## " 
      Write-Warning $Error[0]
     } # End Catch
    
    Stop-Transcript

stop-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

이것은 에 합니다 합니다.-ComputerName remotePC될가다aoes가$remotePC는끈끈"remotePC" -Name Spooler도 동일에 도 도)

제가 알기로는 지금 확인할 수 없는 한, Stop-Service cmdlet 또는 with로는 원격 서비스를 중지할 수 없습니다.넷, 지원되지 않습니다.

예, 작동하지만 원격 컴퓨터가 아닌 로컬 컴퓨터에서 서비스를 중지합니다.

위의 내용이 맞다면 원격 또는 wmi를 실행하지 않고 원격 시스템에서 로컬로 Stop-Service를 실행하는 예약된 작업을 설정할 수 있습니다.

언급URL : https://stackoverflow.com/questions/10342486/using-powershell-to-stop-a-service-remotely-without-wmi-or-remoting

반응형