7

I'm currently trying to use Powershell to connect to a remote desktop, run a program on that desktop, and then log off. I am then checking the output of running that command across a fileshare. Basically this means that PowerShell should wait for the process to complete before continuing.

After reading up, I've been trying to use the Start-Process -Wait option to make sure that it waits for the process to run. However, this script must be run as a scheduled task, and it seems that whenever the script is run when the user is not logged in, the -wait does not work and the script continues on without the process completing. I've tried several different options for waiting, but obviously I have to run the scheduled task while the user is logged off to test it, and testing gets exhausting. Here is my current line of code executing this:

$proc = $(start-process $path -Wait)

Note that I've tried using the -NoNewWindow command, but it is not available on my verison of PowerShell.

Anyone have any other ideas for how to make it wait for the process?

panditbandit
  • 73
  • 1
  • 8
  • 1
    Have you looked at using jobs and the wait-job command? – Austin T French Sep 10 '13 at 02:13
  • I have, but it runs into the same problem. The line that is running command immediately claims that it is finished, so the wait-job command acts the same as -wait (of course again only if the user is not logged in). – panditbandit Sep 10 '13 at 15:41
  • 1
    After doing investigations into the issue, I found out the source of the problem. When starting the process through jobs or through start-process, it was taking 3 seconds for the process 'actually' start after calling start-process. So when the wait was called, it was seeing that the process didn't exist, so it assumed it was finished (instead of having not started yet). The .NET method listed below prevents this from happening. – panditbandit Sep 11 '13 at 15:49

1 Answers1

3

You still have the .net way of starting a process and waiting for his death. Have a look to the Process class, methods and properties.

## Start a process
$Proc = [Diagnostics.Process]::Start("calc.exe")

## Start a processus with param
$Proc = [Diagnostics.Process]::Start("notepad.exe", "Fic.txt")

## Wait for a process death
$Proc.WaitForExit()

You can also configure the starting environment

$credential = Get-Credential
$startInfo = New-Object Diagnostics.ProcessStartInfo
$startInfo.UserName = $credential.Username
$startInfo.Password = $credential.Password
$startInfo.Filename = "powershell"

## Start a process with StartInfo 
$startInfo.UseShellExecute = $false
$Proc = [Diagnostics.Process]::Start($startInfo)

## Stop the process
$Proc.Kill()
JPBlanc
  • 70,406
  • 17
  • 130
  • 175
  • This does the trick. I'm not sure why I didn't find this option listed on any other thread I looked into. I know it's dependent on having .NET installed, but for my purposes it works great. – panditbandit Sep 10 '13 at 17:21