16

The script is fairly straight forward. Simply tries to start a bunch of windows services. Execution locally works fine when on the target machine. The script is actually executing fine as well when done via PsExec, it just never returns until I hit the "enter" key on my CMD prompt. This is a problem, because this is being called from TeamCity, and it makes the Agent hang waiting for PsExec to return.

I've tried the following:

  • Adding an exit and exit 0 at the end of the Powershell script
  • Adding a < NUL to the end of the PsExec call, per the answer in this SF question
  • Adding a > stdout redirect

This is how I am actually calling psexec:

psexec \\target -u domain\username -p password powershell c:\path\script.ps1

No matter what I do, it hangs until I the locally on the cmd prompt. After I hit enter, I get the message:

powershell exited on target with error code 0.
Matt
  • 3,171
  • 9
  • 28
  • 33

5 Answers5

13

I know the answer comes late it would have already been figured out, If not it might be useful for future visitors.

STDIN has to be re-directed in powershell execution inorder to be able to come from hang (Here it waits in STDIN). to be able to do this use -inputformat none

powershell -inputformat none -File powershell_script.ps1 will work.

Check - https://connect.microsoft.com/PowerShell/feedback/details/572313/powershell-exe-can-hang-if-stdin-is-redirected

Venfah Nazir
  • 231
  • 2
  • 4
11

Turns out this is a common problem. Found the solution a here. Essentially, if you pipe some data on stdin with cmd it will return propertly after execution (because it is being run via cmd, not powershell).

Example:

psexec \\target -u domain\username -p password cmd /c "echo . | powershell c:\path\script.ps1"
Matt
  • 3,171
  • 9
  • 28
  • 33
5
psexec \\target -u domain\username -p password -d powershell c:\path\script.ps1

Also fixes the problem.

The -d flag for psexec is like "run and exit" in a non-interactive way:

-d Don’t wait for the application to terminate.

Only use for non-interactive applications.

riogezz
  • 51
  • 1
  • 2
0

Powershell is not exiting. Try this command line

Powershell -command script.ps1
uSlackr
  • 6,337
  • 21
  • 36
0

I was running psexec with VBS script and the solution marked as the best (EX: psexec \\target -u domain\username -p password cmd /c "echo . | powershell c:\path\script.ps1") was working for me only during each 3rd or so run. I was keep digging and I found description of each switch

I decided to try "-s" and that what worked for me every single time Here is my example:

call C:\psexec.exe %SERVER_NAME% -u %USERNAME% -p %PASSWORD% -h -s cscript %pathTomyVBSscript%
alexander.polomodov
  • 1,060
  • 3
  • 10
  • 14
Thomas
  • 1