PowerShell Start Process not working when calling from Remote Machine - powershell

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"

Related

MSI installation command works locally, but not over PowerShell Remoting

I am trying to use Invoke-Command to install an MSI on a remote computer. I am creating the session using credentials for a domain admin account, and have verified it connects correctly.
# DEBUG: Test that the connection is running as admin.
$IsAdmin = Invoke-Command -Session $Session -ScriptBlock {[bool] (net session 2>$null)}
Write-Verbose "Is running as admin: $IsAdmin"
# Now we need to run the MSI install file.
$TempInstallFile = Join-Path -Path $TempDir -ChildPath $InstallFile
$Script = "Start-Process $TempInstallFile -Wait -ArgumentList '/quiet COLLECTORAGENTLIST=`"$CollectorIP`:$CollectorPort`" PORTPOOLRANGES=`"$Ports`" MAXPORTRANGESPERSESSION=""2"" PORTNUMPERALLOC=`"200`" LOGLEVEL=`"3`" SSLMODE=`"2`"'"
Write-Verbose "Installation command: $Script"
Invoke-Command -Session $Session -ScriptBlock {$Script}
The verbose output:
VERBOSE: PSSession to RDPServer created
VERBOSE: Is running as admin: True
VERBOSE: Installation command: Start-Process C:\temp\TSAgent_Setup_5.0.0301.msi -Wait -ArgumentList '/quiet COLLECTORAGENTLIST="REMOVED:8002" PORTPOOLRANGES="1024-49151" MAXPORTRANGESPERSESSION="2" PORTNUMPERALLOC="200" LOGLEVEL="3" SSLMODE="2"'
VERBOSE: PSSession to RDPServer closed
Nothing happens though. The program is not installed on the remote computer and there are no errors. When I copy the "Installation Command" directly from the output, however, and run it in an admin PowerShell on the remote machine, it installs the program correctly. So there must be some issue with the PowerShell remote session, no? I am fairly new to this, what am I missing here?

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"}

Unable to execute EXE remotely using Powershell

There is an exe file on backup server “Backupsrv” C:\Program files\Veritas\NetBackup\bin\admincmd\bpdbjobs.exe.
When I run this exe on “Backupsrv” using PowerShell it is giving some output on console
& "C:\Program Files\Veritas\netbackup\bin\admincmd\bpdbjobs.exe" -all_columns
Now I tried to run this exe from an application server remotely using Invoke-Command as below.
$result = Invoke-Command -ComputerName "backupsrv" -Credential $cred -ErrorAction Stop -ScriptBlock {
& "C:\Program Files\Veritas\netbackup\bin\admincmd\bpdbjobs.exe" -all_columns
}
No result When executed remotely.
The exe is being executed but not giving any result.

Automated Uninstall Service via MSI Not Working

I am writing a powershell script to deploy a .NET 4 Windows Service to a 2008 server via a generated MSI. A fresh installation runs fine, but when I rerun and it tries to uninstall it, the script hangs while trying to do the uninstall. I call msiexec, which runs on the target machine (I can see the process started when the uninstall is running). The only differences between the uninstall and install code is the log name and the /x command passed to msiexec.
Here is the code that I have:
function UninstallService ($serverName, $fileName)
{
write "Start uninstall service."
$msiNamePath = "C:\MsiDeployment\" + $fileName
$processArgs = #("/i", $msiNamePath, "/x", "/qn", "/norestart", "/l", "c:\msiuninstall.log")
# Create session
$session = New-PSSession -ComputerName $serverName
# Enter session
Enter-PSSession $session
# Do uninstall
Invoke-Command -Session $session -ScriptBlock { param($pArgs,$rootDir) Start-Process -FilePath "$rootDir\msiexec.exe" -ArgumentList $pArgs -Wait } -Args $processArgs,("$env:systemroot\system32")
# Close session
Exit-PSSession
Remove-PSSession $session
if (!$?) { throw "Could not uninstall the service remotely on machine " + $serverName }
write "End uninstall service."
}
If I terminate the running msiexec on the server, the script continues on processing (fails later due to checking if the service is uninstalled). I'm guessing that there is some prompt that is looking for user input (maybe UAC), but I'm not entirely certain. I get no log file on the uninstall, but install writes the log file.
Enter-PSSession is meant only for interactive use and not in a script. So, essentially, your script stops working after Enter-PSSession $session.
Remove the following lines from your script and everything should work as expected.
# Enter session
Enter-PSSession $session
# Close session
Exit-PSSession
All you need is the Invoke-Command.
Actually, I figured out the issue. I left the /i flag in the arguments when it should have just been the /x flag. Works fine now.
The flag was the msiexec throwing an error page even when the qn flag was passed to it. Not sure if it should have done that.

How to remote execute an ELEVATED remote script in 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"