How to remote execute an ELEVATED remote script in PowerShell - powershell

I have two servers:
serverA (windows 2003 server)
serverB (windows 7)
ServerA contains a folder with a batch file (deploy.bat) that needs to be executed from an elevated powershell prompt. In ServerA, if I run it from a normal prompt or powershell prompt it fails. If I run it from an elevated prompt it works. (run as administrator).
The problem I have is when I try to execute batch file from serverB using a remote powershell execution. I am able to execute with this command:
Invoke-Command -computername serverA .\remotedeploy.ps1
The content of remotedeploy.ps1 is:
cd D:\Builds\build5
.\Deploy.bat
I have looked a lot questions in stackoverflow about:
Execute a remote powershell (This works for me)
Execute a local powershell with elevated prompt (I can do it)
This question is about both at the same time. So the exact question is:
Is possible to execute an ELEVATED REMOTE script in PowerShell?

If you're using PowerShell 4, you can execute the command using Desired State Configuration, which run as SYSTEM:
Invoke-Command -ComputerName ServerA -ScriptBlock {
configuration DeployBat
{
# DSC throws weird errors when run in strict mode. Make sure it is turned off.
Set-StrictMode -Off
# We have to specify what computers/nodes to run on.
Node localhost
{
Script 'Deploy.bat'
{
# Code you want to run goes in this script block
SetScript = {
Set-Location 'D:\Builds\build5'
# DSC doesn't show STDOUT, so pipe it to the verbose stream
.\Deploy.bat | Write-Verbose
}
# Return $false otherwise SetScript block won't run.
TestScript = { return $false }
# This must returns a hashtable with a 'Result' key/value.
GetScript = { return #{ 'Result' = 'RUN' } }
}
}
}
# Create the configuration .mof files to run, which are output to
# 'DeployBot\NODE_NAME.mof' directory/files in the current directory. The default
# directory when remoting is C:\Users\USERNAME\Documents.
DeployBat
# Run the configuration we just created. They are run against each NODE. Using the
# -Verbose switch because DSC doesn't show STDOUT so our resources pipes it to the
# verbose stream.
Start-DscConfiguration -Wait -Path .\DeployBat -Verbose
}

Do you try to change remoteDeploy.ps1 to start CMD.EXE with elevated rights :
cd D:\Builds\build5
start-process CMD.EXE -verb runas -argumentlist "-C",".\Deploy.bat"

Related

Powershell start-process can't find file

I am trying to upgrade a server with a particular application from a client by PowerShell remote:
Invoke-Command -ComputerName $server -Credential $mycreds {Start-Process -FilePath "C:\temp\xxx.exe" -ArgumentList "-default", "-acceptEULA" -wait }
Whatever I try, I get messages like "Can't find the file specified..." what do I do wrong?
FilePath is on the local (client) computer.
Your C:\temp\xxx.exe executable must be present on the server (the remote machine) for your command to work, because that is where your script block ({ ... }) executes.
Note: By contrast, if you use Invoke-Command with the -FilePath parameter in order to run a locally present script file (.ps1) remotely, PowerShell automatically copies it to the remote machine; from the docs: "When you use this parameter, PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer."
To copy the executable there from your local (client-side) machine, you need a 4-step approach (PSv5+, due to use of Copy-Item -ToSession[1]):
Create a remoting session to $server explicitly, using New-PSSession
Copy the local (client-side) executable to that session (the remote computer) with Copy-Item and its -ToSession parameter
Run your Invoke-Command command with the -Session parameter (rather than -ComputerName) in order to run in the explicitly created session (this isn't strictly necessary, but there's no need to create another (ad hoc) session).
Run Remove-PSSession to close the remote session.
Important: In a PowerShell remoting session, you cannot run external programs that require interactive user input:
While you can launch GUI applications, they invariably run invisibly.
Similarly, interactive console applications aren't supported (although output from console applications is received by the client).
However, interactive prompts from PowerShell commands are supported.
To put it all together:
# Specify the target server(s)
$server = 'w764' # '.'
# Establish a remoting session with the target server(s).
$session = New-PSSession -ComputerName $server
# Copy the local executable to the remote machine.
# Note: Make sure that the target directory exists on the remote machine.
Copy-Item C:\temp\xxx.exe -ToSession $session -Destination C:\temp
# Now invoke the excutable on the remote machine.
Invoke-Command -Session $session {
# Invoke *synchronously*, with -Wait.
# Note: If the program is a *console* application,
# you can just invoke it *directly* - no need for Start-Process.
Start-Process -Wait -FilePath C:\temp\xxx.exe -ArgumentList "-default", "-acceptEULA"
}
# Close the remote session.
# Note: This will terminate any programs that still
# run in the remote session, if any.
Remove-PSSession $session
[1] If you're running Powershell v4 or below, consider downloading psexec.

Unable to run the parametrized batch file on remote machine using PowerShell

Execute the remote server parametrized batch file from PowerShell.
Doesn't throw an error nor executed command on remote machine.
$path = "D:\run\test-5.2.bat";
Invoke-Command -ComputerName testserver -Scriptblock { "$path" }
Script inside the bat file is msiexec with parameters, which shall execute through Command Prompt only.
Based on this msdn link, you can run a ps1 script file on remote computers. So if it is possible to "port" the content of the bat file in a ps1 it should work. Here is the msdn example:
Example 11: Run a script on all the computers listed in a text file
PS C:\> Invoke-Command -ComputerName (Get-Content Servers.txt) -FilePath C:\Scripts\Sample.ps1 -ArgumentList Process, Service
This example uses the Invoke-Command cmdlet to run the Sample.ps1 script on all of the computers listed in the Servers.txt file. The command uses the FilePath parameter to specify the script file. This command lets you run the script on the remote computers, even if the script file is not accessible to the remote computers.
When you submit the command, the content of the Sample.ps1 file is copied into a script block and the script block is run on each of the remote computers. This procedure is equivalent to using the ScriptBlock parameter to submit the contents of the script.
Hope that helps
$path is a string. PowerShell simply echoes bare strings instead of executing them, unlike CMD or bash. Use the call operator (&):
& "$path"
or Start-Process:
Start-Process cmd.exe -ArgumentList '/c', $path -NoNewWindow -Wait
to have PowerShell execute a string as a command. Since you say you're running msiexec.exe from the batch script using the latter may be required.
On top of that you have a scope issue. The variable $path inside the scriptblock is not the same as the one in the global scope. You can mitigate that via the using: scope qualifier:
Invoke-Command -Computer testserver -Scriptblock { & "$using:path" }
or by passing $path as an argument to the scriptblock:
Invoke-Command -Computer testserver -Scriptblock { & "$($args[0])" } -ArgumentList $path

Using PowerShell to execute a remote script that calls a batch file

I am having an issue with running a batch file that is located on a remote server.
I have a batch file located on a remote server that i want to run that kicks off an automated Selenium test. For simplicity, let's say the name of my batch file is mybatch.bat
I have the following code in a Powershell script located on the server:
$BatchFile = "mybatch.bat"
Start-Process -FilePath $BatchFile -Wait -Verb RunAs
If I run this PowerShell script locally on the server in ISE then it runs fine and it kicks off the selenium test which takes a couple minutes to run.
Now I want to try to execute this test from another machine by using PowerShell remoting. Let's assume that remoting is already configured on the servers.
I have a PowerShell script located on another server which has the following code segment. Assume that all of the session variables have the correct information set:
$CMD = "D:\mybatch.bat"
$TargetSession = New-PSSession -ComputerName $FullComputerName -Credential $myCreds -ConfigurationName RemoteExecution
$command = "powershell.exe -File $CMD -Wait"
Invoke-Command -Session $TargetSession -ScriptBlock { $command }
When this script runs, it does connect to the remote machine and create a remote session. It does look like it kicks off the batch file because PowerShell does not give me an error. But it does not wait for the full 3 or 4 minutes for the Selenium test to finish. It seems like it just times out. Also if I am logged onto the other machine, I don't see any Selenium web test running. No Selenium log files or results files are created on remote server as should be expected.
I was wondering what I could be doing wrong with my code.
Also, it seems that the server always returns the echo outputs of the batch file to my local machine. I see these random blinking white screen on ISE which looks like output from the batch file
$command = "powershell.exe -File $CMD -Wait"
Invoke-Command -Session $TargetSession -ScriptBlock { $command }
There are 2 issues with the above code:
$command inside the scriptblock and $command outside the scriptblock are different variables due to different scopes. The variable inside the scriptblock is thus undefined and the scriptblock will simply echo an emtpy value.
Even if $command weren't undefined, the scriptblock would still just echo its value, since it's defined as a string. PowerShell does not execute strings unless you're using something like Invoke-Expression (which you shouldn't).
This should do what you want:
$CMD = "D:\mybatch.bat"
$TargetSession = New-PSSession -ComputerName $FullComputerName -Credential $myCreds -ConfigurationName RemoteExecution
Invoke-Command -Session $TargetSession -ScriptBlock { & $using:CMD }
If you would like execute a bat file from another machine by using PowerShell Remote Session, simply enter dot and then follow by a whitespace, then enter the exact path of bat file located on that remote machine.
Example
Invoke-Command -ComputerName RemoteComputerName -Credential $credential -ScriptBlock {. "D:\Temp\Install_Something.bat"}

PowerShell Invoke-Command using Start-Process is not creating log file

I have a command line exe on a remote server which I need to execute remotely (running on the remote server). This exe connects to the DB, and writes a log file.
I have enabled WinRM by executing these PowerShell commands:
netsh http add iplisten localip {add local ip here}
netsh http add iplisten 127.0.0.1
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*" -Force
Enable-PSRemoting -Force
This works and I was able to test by executing
Test-WSMan {computername}
I am now trying to execute the command line exe via Invoke-Command and expecting a log file entry to be created with this script.
Invoke-Command –ComputerName MyServer –ScriptBlock {
Start-Process "C:\TheRemotePath\ToTheExe.exe"
}
PowerShell does not display any errors. However, no log file is generated. I have full rights to the directory of the exe as well as the log file directory. I am able to successfully run the exe via Windows Explorer (navigate to the remote exe and double click to run).
Any idea why this does not seem to work or what tools I can use to try and diagnose?
I would try testing the path and switching to the call operator as Ansgar mentioned, i.e.:
Invoke-Command –ComputerName MyServer –ScriptBlock {
$path = "C:\TheRemotePath\ToTheExe.exe"
if (Test-Path $path) {
Write-Host -ForegroundColor Green "Confirmed access to $path!"
& $path
}
else {
Write-Host -ForegroundColor Yellow "Unable to reach $path!"
}
}
Doing those will help you diagnose where it's getting tripped up. Depending on the EXE, I've had to use different methods of starting the process from Powershell.
Change the working directory to the location of your executable before running it. I would also recommend using the call operator (&) instead of Start-Process, unless you have reason to use the latter.
Invoke-Command –ComputerName MyServer –ScriptBlock {
Set-Location 'C:\MyDirectory'
& 'MyApp.Console.exe'
}

PowerShell Start Process not working when calling from Remote Machine

I am trying to execute the following powershell script from a Remote machine. It is working fine when running the script locally.
I am able to see the notepad, when I execute it from remote machine, I am not able to see any notepad.exe process in Task Manager.
OpenNotepad.ps1:
Start-Process notepad.exe
if($?)
{
write-host "SUCCESS"
}
else
{
write-host "FAIL"
}
My Remote Script
Invoke-Command -Session $session -command "C:\Users\username\Desktop\OpenNotepad.PS1"