Search code examples
powershellpowershell-remotingelevated-privileges

Using Invoke-Command to run Start-Process in an elevated session


As a precursor to running an installation file on several remote servers, I need to update the Powershell setting MaxMemoryPerShellMB. This requires running a PS session as Administrator on the remote server. I have been trying to run Invoke-Command which then runs a ScriptBlock consisting of a Start-Process command which includes the -Verb RunAs parameter. Nothing seems to work, however.

I have tried with various quoting schemes, single, double, triple, but nothing seems to work.

I've tried running the Start-Process from an Enter-PSSession, with the same results.

Following is the code I'm testing now:

$creds = Get-Credential -Username 'DOMAIN\userID' -Message "Enter Username and Password to access the remote servers."

$ScriptBlock = {
    Start-Process -FilePath Powershell.exe -ArgumentList """Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024""" -Verb RunAs -Wait 
}
Invoke-Command -ComputerName testsvr01 -Credential $creds -ScriptBlock $ScriptBlock

I should be able to RDP to the remote server and run Get-Item WSMan:\localhost\Shell and have it show the updated value, but the value isn't changed.

When running the code it pauses for a second when the Invoke-Command runs, but other than that, there is no feedback in Powershell.

On the remote server I see the following two Kerberos errors in the System Event log.

0x19 KDC_ERR_PREAUTH_REQUIRED,

0xd KDC_ERR_BADOPTION

Any help is greatly appreciated.


Solution

  • > powershell.exe -?
    ...
    EXAMPLES
    ...
    PowerShell -Command "& {Get-EventLog -LogName security}"
    
    -Command
    ...
     To write a string that runs a Windows PowerShell command, use the format:
        "& {<command>}"
    where the quotation marks indicate a string and the invoke operator (&)
    causes the command to be executed.
    

    So you could try to call Set-Item in the following way:

    $ScriptBlock = {
        Start-Process -FilePath Powershell.exe -ArgumentList "-Command"," &{ Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 1024 }" -Verb RunAs -Wait -PassThru
    }
    $process = Invoke-Command -ComputerName testsvr01 -Credential $creds -ScriptBlock $ScriptBlock
    $process.ExitCode
    

    I'm also returning a process object via -PassThru on which you might check the `ExitCode``

    Hope that helps