powershellserviceelevated-privilegesstart-process

PS1 Restart service as specified user


I'm trying to create a PS1 script to restart a service in a computer, where the user has no admin right, so i'm trying to execute as de admin user, now i'm trying first to open Notepad, but when I execute this script:

# Define el nombre del servicio, usuario y contraseña
$ServiceName = "ApacheDtdlIdServer"
$AdminUser = "User"
$AdminPassword = "C0ntraseña"
$startWithElevatedRights = "notepad"

# Convierte la contraseña en un SecureString
$SecurePassword = ConvertTo-SecureString $AdminPassword -AsPlainText -Force

# Crea el objeto de credenciales
$credentials = New-Object System.Management.Automation.PSCredential ($AdminUser, $SecurePassword)

$ps = Start-Process -PassThru -FilePath powershell -Credential $credentials -ArgumentList '-noprofile -command &{Start-Process ',  $startWithElevatedRights, ' -Wait -verb runas}'

$ps.WaitForExit()

I get the error:

Start-Process: This command cannot be executed due to the error: The directory name is > invalid. At C:\Users\IsaacSanzIT\Desktop\Rider\RestartScanner.ps1: 13 Character: 7

I've tried the things that says in other questions in StackOverflow, like this one using the Runas, anyone know how to execute the notepad, or even restart a a service using the admin account? Thanks!


Solution

  • Therefore:

    $ps = 
      Start-Process -WorkingDirectory C:\ -PassThru -Credential $credentials powershell @"
    -noprofile -c Start-Process -Wait -Verb RunAs $startWithElevatedRights
    @"
    

    [1] Note that while administrators can usually access all directories that a given user can, this only applies if the process running with the administrator user identity is already elevated. However, because Start-Process doesn't allow you to simultaneously launch a process as another user and with elevation, the outer Start-Process call - the one that uses -Credential - must of necessity create a non-elevated process first, and only in a second step is elevation as that user then possible (the nested Start-Process -Verb RunAs call); see this answer for details.