如何在powershell中刷新远程计算机上的服务状态?

如何在powershell中刷新远程计算机上的服务状态?,powershell,Powershell,此脚本用于检查服务器1上是否启动了服务,如果未启动,则启动服务 $cred = Import-Clixml -Path F:\Powershell\Safe\xxxx.txt $server1 = Invoke-Command -ComputerName xxxx -ArgumentList $servicename -ScriptBlock { Param($servicename) Get-Service -Name $servicename } -Credential $

此脚本用于检查服务器1上是否启动了服务,如果未启动,则启动服务

$cred = Import-Clixml -Path F:\Powershell\Safe\xxxx.txt 
$server1 = Invoke-Command -ComputerName xxxx -ArgumentList $servicename -ScriptBlock {
    Param($servicename)
    Get-Service -Name $servicename
} -Credential $cred

if ($server1.Status -eq "Running"){
    Write-Host "The Telephony service is started on xxxx"
} else {
    Write-Host "The Telephony service is stopped on xxxx, starting up service"
    Start-Sleep -Seconds 5
    Invoke-Command -ComputerName xxxx -ArgumentList $servicename -ScriptBlock {
        Param($servicename)
        Start-Service -Name $servicename
    } -Credential $cred
    Write-Host "Telephony service is starting xxxx"
    Start-Sleep -Seconds 10
    $server1.Refresh()
    if ($server1.status -eq "Running") {
        Write-Host "Telephony service is now started on xxxx"
    } else {
        Write-Host "The Telephony service failed to start on xxxx please check services and try again."
我得到一个错误声明:

方法调用失败,因为[Deserialized.System.ServiceProcess.ServiceController]不包含名为“refresh”的方法


但是,在本地服务而不是远程PC上使用
$server.Refresh()
命令时,工作正常。如何刷新远程PC上服务状态的变量?

每次需要使用脚本的第二行获取状态时,都必须查询服务。方法在序列化时被剥离,这发生在从远程服务器返回对象时。每次要获取该服务的当前状态时,您都需要运行:

$server1 = Invoke-Command -ComputerName xxxxxxxxx -ArgumentList $servicename -ScriptBlock {Param($servicename) Get-Service -name $servicename} -Credential $cred
或者将所有这些都放在一个脚本块中,并在远程服务器上完成

$cred = Import-Clixml -path F:\Powershell\Safe\xxxxxxxx.txt 

$SBlock = {
    Param($servicename)

    $Service = Get-Service -name $servicename
    if ($Service.Status -eq "Running"){
        "The Telephony service is started on xxxxxxxxx"
    }
    Else{
        "The Telephony service is stopped on xxxxxxxxx, starting up service"
        start-sleep -seconds 5
        Start-Service -name $servicename
        "Telephony service is starting xxxxxxxxx"
        start-sleep -seconds 10
        $Service.Refresh()
        if ($server1.status -eq "Running"){
            "Telephony service is now started on xxxxxxxxx"
        }
        else {
            "The Telephony service failed to start on xxxxxxxxx please check services and try again."
        }
    }
}

Invoke-Command -ComputerName xxxxxxxxx -ArgumentList $servicename -ScriptBlock $SBlock -Credential $cred