Friday, March 5, 2010

Setting the Working Directory for a Spawned Process

As one would expect, PowerShell is very capable of launching processes. Sometimes, it is necessary to launch a process that doesn't block (such as a user-interface based application) and wait for it to close.

Here is a little snippet of code to do this:

$p = [diagnostics.process]::start("something.exe", "--arg1 --arg2")
$p.WaitForExit()

One limitation is that the "Working Directory" of the spawned process is set to the user's home directory by default, which is often unacceptable. Here is another little snippet that explicitly sets the working directory to the current directory before spawning the process:

$psi = New-Object  System.Diagnostics.ProcessStartInfo("something.exe", "--arg1 --arg2")
$psi.WorkingDirectory = (Get-Location).Path
$p = [Diagnostics.Process]::Start($psi)
$p.WaitForExit()

This took me just enough time to figure out on my own where I thought it warranted a blog posting. Happy scripting...

No comments: