Tuesday, 19 April 2011

Doing a 'start /wait' in PowerShell

Countless times I’ve had to write a script that would start a process, normally some sort of installation routine, but have needed to ensure that the process had finished doing its thing before passing control back to the script.  Normally if you’re writing a batch/cmd file you’d do something like this..

start /wait notepad.exe  

..or in VBscript something like this..

Set objShell = Wscript.CreateObject("Wscript.Shell")
objShell.Run("notepad.exe"),1,True  

As part of our Windows 7 rollout here at the Uni I want to reduce the number of startup/shutdown & logon/logoff scripts and if we have to script something then it would be done in PowerShell.  As such I’ve needed to reproduce the ‘start /wait’ type functionality that I’ve used before in .cmd & .vbs scripts in a .ps1.  After a bit of research seems like the easiest way to do it is with something like this:

$process = [System.Diagnostics.Process]::Start("notepad.exe")
$process.WaitForExit()  

And passing parameters is easy as well, you just need something like:

$process = [System.Diagnostics.Process]::Start("notepad.exe","c:\temp\sometextfile.txt")
$process.WaitForExit()  

No comments:

Post a Comment