PowerShell远程服务状态刷新报错,如何更新远程服务状态变量?
Refresh()方法的问题 Hey there! Let's break down why you're hitting that error and fix it up.
问题根源
When you use Invoke-Command to fetch a service object from a remote machine, PowerShell serializes and deserializes the object for transmission. The result you get back is a Deserialized.System.ServiceProcess.ServiceController object—not the live ServiceController instance you'd get locally. This deserialized copy only holds the object's property data, not its original methods like Refresh()—hence the "method not found" error.
解决方案
Instead of trying to call Refresh() on the stale deserialized object, you need to re-query the remote machine to get the latest service state. Here's your revised script with this fix, plus a few small improvements for maintainability:
$cred = Import-Clixml -Path F:\Powershell\Safe\xxxx.txt $servicename = "Telephony" # Make sure this matches your actual service name $targetServer = "xxxx" # Centralize server name for easier updates # Initial service status check $serviceStatus = Invoke-Command -ComputerName $targetServer -ArgumentList $servicename -ScriptBlock { Param($servicename) Get-Service -Name $servicename } -Credential $cred if ($serviceStatus.Status -eq "Running"){ Write-Host "The Telephony service is started on $targetServer" } else { Write-Host "The Telephony service is stopped on $targetServer, starting up service" Start-Sleep -Seconds 5 # Start the remote service Invoke-Command -ComputerName $targetServer -ArgumentList $servicename -ScriptBlock { Param($servicename) Start-Service -Name $servicename } -Credential $cred Write-Host "Telephony service is starting on $targetServer" Start-Sleep -Seconds 10 # Re-query for updated status (replaces the broken Refresh() call) $serviceStatus = Invoke-Command -ComputerName $targetServer -ArgumentList $servicename -ScriptBlock { Param($servicename) Get-Service -Name $servicename } -Credential $cred if ($serviceStatus.Status -eq "Running") { Write-Host "Telephony service is now started on $targetServer" } else { Write-Host "The Telephony service failed to start on $targetServer please check services and try again." } }
Key Fixes & Improvements
- Replaced
$server1.Refresh()with a freshInvoke-Commandcall to pull the latest service state from the remote machine. - Added
$targetServerand explicitly defined$servicenameto make the script easier to update and debug. - Fixed the missing closing curly brace at the end of your original script to avoid syntax errors.
内容的提问来源于stack exchange,提问作者KN619

