powershellpowershell-remotingwinrm

How do I remotely reset the WinRM service using PowerShell?


When re-registering a configured PowerShell session with the same name as before, the WinRM service might (more often than not) need to be restarted.

My issue is that this needs to be done remotely in my environment. Thus, this sequence of commands below will fail if not run locally...

Invoke-Command 'RemoteServer' {
  Unregister-PsSessionConfiguration -Name 'MySession' -Force
  Restart-Service WinRM -Force # This will of course kill the current WinRM connection 
  Register-PsSessionConfiguration -Name 'MySession'
}

Is there a safe way to do an Unregister-PsSessionConfiguration, using the same name later on, without the need of restarting the WinRM service?

A work around would, of course, be to run this as a Scheduled Task to keep the session doing the reset from being terminated.

As a note, you should always set up registered sessions with the option -SecurityDescriptorSddl to keep it from being accessed by any administrator.


Solution

  • Ok, Scheduled Tasks was the way to go...
    To keep the code more readable, I've only provided some of the parameters needed to set up a scheduled task using PowerShell.

    You won't be able to run this example straight of.

    $Online = $null
    while (!$Online) {# Make sure remote connection is possible first
      try {$Online = Invoke-Command 'RemoteServer' {$true} -ErrorAction Stop}
      catch {$Online = $false}
    }
    
    try {
      Invoke-Command 'RemoteServer' {# Kill WinRM (also killing this session)
        Unregister-PsSessionConfiguration -Name 'MySession' -Force
    
        $RestartWinRM = {# Code for restarting WinRM using Scheduled Task}
    
        Register-ScheduledTask `
          -TaskPath '.' -TaskName 'Restart WinRM' `
          -Action $RestartWinRM
    
        Start-ScheduledTask -TaskPath '.' -TaskName 'Restart WinRM' 
      }
    }
    catch {# The error when this session terminates
    }
    
    $Online = $null
    while (!$Online) {# Make sure remote connection is possible again
      try {$Online = Invoke-Command 'RemoteServer' {$true} -ErrorAction Stop}
      catch {$Online = $false}
    }
    
    Invoke-Command 'RemoteServer' {# Register the session configuration again
      Register-PsSessionConfiguration -Name 'MySession'
    }