Question

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?

Was it helpful?

Solution

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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top