为什么Windows远程管理服务坚持"延迟启动"?

tnw*_*tnw 2 powershell windows-services powershell-remoting

我遇到了WinRM服务的一些问题.它一直坚持要求"延迟启动(自动)"服务,而不仅仅是"自动"服务.

为什么?这导致我的VM出现问题(在Hyper-V上).我通过PowerShell以编程方式将它们还原,然后需要通过PowerShell远程处理来访问它们,但有时当我第一次将虚拟机联机时,WinRM服务还没有启动(它们是"完全启动",就像我可以登录它们一样).

如果我将服务设置为自动,则运行PowerShell命令winrm quickconfig表示该服务未设置为远程处理,并且坚持将服务设置回延迟启动.

在尝试打开远程PowerShell会话之前,如何确保Windows RM服务正在运行?

Mit*_*tul 6

关于为什么在引导过程(延迟启动)之后可能加载某些服务的基本原因是:

  1. 提高服务器的启动性能并具有一定的安全性.

  2. 某些服务依赖于其他服务来启动.对于Windows远程管理服务,它取决于以下服务
    a.HTTP服务
    b.远程过程调用(RPC)(自动)
    i.DCOM服务器进程启动器(自动)
    ii.RPC端点映射器(自动)

在尝试打开远程PowerShell会话之前,如何确保Windows RM服务正在运行?

看看我写的以下选项和功能,以便做你想做的事情.

A)您可以使用Test-Connection检查计算机是否在线.

Test-Connection -ComputerName $Computer -Count 1 -Quiet
Run Code Online (Sandbox Code Playgroud)

B)我创建StartWinRMIfStopped了将使用WMI启动"WinRM"服务的函数.

C)第二个功能是TryToCreateNewPSSession尝试创建一个新的PSSession或应该给你的异常对象

param([string]$server)
Get-PSSession | Remove-PSSession
$newsession = $null
function StartWinRMIfStopped
{
param([string]$ComputerName)
    Write-Host $ComputerName
    $WinRMService = Get-WmiObject -Namespace "root\cimv2" -class Win32_Service -Impersonation 3 -ComputerName $ComputerName | Where-Object {$_.Name -match "WinRM"}
    if($WinRMService.State -eq "Stopped" -or $WinRMService.State -eq "Paused"){
        "WinRM Service is" + $WinRMservice.State
        $WinRMService.StartService()
    }
    else{
        "WinRM Service is " + $WinRMservice.State
    }
}
function TryToCreateNewPSSession{
    param([string]$computerName)
    Try
    {
        $newsession = New-PSSession -Computer $computerName -ErrorAction Stop    
        #Connect-PSSession -Session $newsession
        $newsession        
    }
    Catch [System.Management.Automation.RuntimeException]{    
        if($error.Exception.Gettype().Name -eq "PSRemotingTransportException"){
            Write-host "WinRM service is not started on the server"
        }
        Write-host "RuntimeException occured in creating new PSSession to the Server"
    }
    Catch [Exception]{
        Write-host "Generic Exception while creating PSSession"
    }
}

$error.Clear()
If (Test-Connection -Computer $server -count 1 -Quiet) { 
#Connection to server successfull    
StartWinRMIfStopped $server
Start-Sleep -s 4
#Invoke Command on remote server using trytocreatenewpssession function.
Invoke-Command -Session (TryToCreateNewPSSession $server) -ScriptBlock { write-host "hello world"}
}
Run Code Online (Sandbox Code Playgroud)

您可以调用整个脚本

PS C:\> .\ScriptName.ps1 remotecomputername
Run Code Online (Sandbox Code Playgroud)