我遇到了这个似乎有效的衬垫:
stop-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么,因为我认为停止服务不起作用,除非您使用远程处理或它发生在本地主机上.
Kei*_*ill 37
输出Get-Service是一个System.ServiceProcess.ServiceController可以在远程计算机上运行的.NET类.它是如何实现的,我不知道 - 可能是DCOM或WMI.一旦你从其中获得了其中一个Get-Service,它就可以被传递到Stop-Service很可能只是Stop()在这个对象上调用方法.这会停止远程计算机上的服务.事实上,你也可以这样做:
(get-service -ComputerName remotePC -Name Spooler).Stop()
Run Code Online (Sandbox Code Playgroud)
感谢大家对这个问题的贡献,我想出了以下脚本。更改值$SvcName,并$SvrName根据您的需要。如果远程服务停止,此脚本将启动远程服务,如果已启动,则将其停止。它使用cool.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)"
}
Run Code Online (Sandbox Code Playgroud)
当然,您运行它的帐户需要适当的权限才能访问远程计算机并启动和停止服务。在对较旧的远程计算机执行此操作时,您可能首先必须在较旧的计算机上安装 WinRM 3.0。
| 归档时间: |
|
| 查看次数: |
98701 次 |
| 最近记录: |