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

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.

> 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

Related

Install MSI on remote computer using Powershell

I am trying to write a Powershell script which will deploy software on a collection of WS2016 servers. I am a local administrator on all these servers. Here's what I have so far:
$Cred = Get-Credential
$Computer = 'myserver.contoso.com'
$SplunkMSI = '\\mylocalbox\C$\Splunk.msi'
$InstallDir = 'C:\Apps\Splunk\'
$sb = {
param($installer, $dir)
Start-Process -FilePath 'c:\windows\system32\msiexec.exe' -ArgumentList "$installer INSTALLDIR=$dir AGREETOLICENSE=Yes /qn /norestart /L*v C:\temp\splunkInstall.log" -Wait -NoNewWindow
}
Write-Host "Deploying Splunk to host $Computer"
Invoke-Command -Computer $Computer -Credential $Cred -ScriptBlock $sb -ArgumentList $SplunkMSI, $InstallDir -ErrorAction Stop
When I run this script, I get prompted for credentials, and then I see the output of the Write-Host, but then... nothing. I have to manually terminate the script.
I logged onto the remote host, but see no evidence that the MSI was executed or failed to execute.
Anyone see a smoking gun?
ya, it looks like it's looking for $installer and $dir in the script block but they're not specified

How to make powershell wait for a batch file to complete the execution of all comand on remote-server

$storesess = New-PSSession -ComputerName marshy -Credential marshy001
Enter-PSSession -Session $storesess
Invoke-Command -ScriptBlock {start-process C:\Users\marshmellow\Documents\Some\xyz.bat }
Exit-PSSession
Above is the script which calls a bat file saved on remote server C:\Users\marshmellow\Documents\Some\xyz.bat
The bat file has two commands one which sets the working directory using "pushd" and another which stops a application process. The second command takes a couple of minutes to complete. I have found that the Start-Process doesn't wait for the second command to complete successfully, it just fires the command and closes the process.
Is there any way to make the Start-Process wait for the command to get completed successfully as I have already tried using -Wait which doesn't work.
If there's a way to even open a cmd session on the remote server and pass few commands in it saved in variables and that output is relayed to my PowerShell script even that is fine. can anyone please help?
Using cmd.exe might work?
Invoke-Command -ScriptBlock {
cmd /k "C:\Users\marshmellow\Documents\Some\xyz.bat"
} -ErrorAction Stop
If not, you could probably Start-Process -Wait on cmd.exe, then supply the batch commands as an -ArgumentList
What do you get if you try this?
Invoke-Command -FilePath $PathToBatchFile
You do not need the Invoke-Command cmdlet. Just use Start-Process with the -Wait parameter and pass the correct parameters to cmd:
$storesess = New-PSSession -ComputerName marshy -Credential marshy001
Enter-PSSession -Session $storesess
Start-Process cmd -ArgumentList "/C C:\Users\marshmellow\Documents\Some\xyz.bat" -Wait
Exit-PSSession

Executing batch file in the remote machines using powershell as a background job

All I am trying to do is to execute a batch file in remote machines as a job.I have batch file located in all machines inside C:\Users\temp folder.Here is my code
$batFile = "test.bat"
foreach($m in $machine)
{
Invoke-Command -ComputerName $m -ScriptBlock{param($batFile) & cmd.exe /c "C:\Users\temp\$batFile"} -Authentication negotiate -Credential $cred -ArgumentList $batFile -AsJob
}
But I keep getting
The expression after '&' in a pipeline element produced an object that was not valid. It must result in a command name, a script
block, or a CommandInfo object
I tried using $using:batFile inside ScriptBlock as well with no success. Can anyone suggest me what I might be doing wrong? I am using powershell version 4.
do a trace on that,
Invoke-Command -ComputerName $m -ScriptBlock{param($batFile) Trace-Command NativeCommandParameterBinder -Expression { & cmd.exe /c "C:\Users\temp\$batFile"}} -Authentication negotiate -Credential $cred -ArgumentList $batFile -AsJob
and Try using Invoke-Expression as a workaround instead of &
invoke-Expression "cmd.exe /c 'C:\Users\temp\$batFile'"
Regards,
Kvprasoon

Run a powershell script on a remote system with elevated permissions to enable remoting

I am trying to use the following code to copy a PowerShell script to remote windows 7 machine; run it with elevated privileges on this machine to enable remoting on that system.
It is copying the script file to the remote system but it is not executing the command in the remote PowerShell session because of the empty $command variable (the second line in the script below is not working).
Copy-Item -Path C:\users\user1\Myscript.ps1 -Destination \\some-computer\c$\Myscript.ps1
$command = PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Myscript.ps1""' -Verb RunAs > C:\PS-result1.txt}"
$cmd = "CMD.EXE /c "+$command
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName "some-computer"
Start-Sleep -s 8
Get-Content \\some-computer\C$\PS-result1.txt
Is it possible to accomplish this?
Thanks,
Using WMI to call CMD to call PowerShell to call Start-Process to call PowerShell again? That seems a little complicated.
Try something much simpler:
$command = "PowerShell.exe ""C:\Myscript.ps1"" > ""C:\PS-result1.txt"""
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $command -ComputerName "some-computer"

Can't start PowerShell script file with credentials of other user

I have a GUI that has been created with PowerShell Studio and exported as a PS1-file. I'm now trying to launch this GUI by calling it with another user's credentials.
When I run the code it doesn't even give an error message. PowerShell pops-up and closes again in seconds and nothing is launched. Follwoing this thread, I think I followed the correct syntax.
$Script = 'S:\Prod\Script center\GUI Script.ps1'
$Credentials = Get-Credential
$powershellArguments = "-file '$Script'", "-noexit", "-verb runas"
Start-Process powershell -Credential $Credentials -ArgumentList $powershellArguments
These ones doesn't work either:
Start-Process powershell -Credential $Credentials -ArgumentList "-noprofile -command &{Start-Process powershell -verb runas -File 'S:\Prod\Script center\GUI Script.ps1'}"
Start-Process powershell -Credential $Credentials -ArgumentList "-noprofile -command &{Start-Process $script -verb runas}"
And this one is asking me the credentials, although they are already saved in the variable $Credentials. However, the powershell console launched is not launched as the user in the Credentials :(
$cmd = 'powershell.exe'
$arguments = "-NoExit", "-NoProfile", "-WindowStyle Maximized", '-NoLogo', "Credential $Credentials", "File '$script'"
Start-Process $cmd -ArgumentList $arguments -Verb runAs
I'm sure it's not related to the GUI script, because this works perfectly fine:
& 'S:\Prod\Script center\GUI Script.ps1'
Any help is greatly appreciated.
Maybe your error is only on argument single quotes $powershellArguments = "-file '$Script'"; double quotes should be used.
Start-Process -FilePath "powershell" -Credential $cred -ArgumentList #("-file 'cred.ps1'") # doesn't work
Start-Process -FilePath "powershell" -Credential $cred -ArgumentList #("-file ""cred.ps1""") # works