Peter Goras
Peter Goras

Reputation: 612

powershell: synchronous stop-process

ok. I want to stop a running process and then continue with the script only once the process has stopped.

for example: stop media player and then delete the media player database (if you have wmp12 you may understand the reason why!) But the rest of the script starts executing before the app has time to shut down.

#stop wmp
stop-process -processname wmplayer
#delete
dir "C:\Users\blergh\AppData\Local\Microsoft\Media Player" -filter *wmdb | foreach { del $_.fullname}

And i get:

Remove-Item : Cannot remove item C:\Users\blergh\AppData\Local\Microsoft\Media Player\CurrentDatabase_372.wmdb: The proces
s cannot access the file 'C:\Users\blergh\AppData\Local\Microsoft\Media Player\CurrentDatabase_372.wmdb' because it is bei
ng used by another process.

Can I force this to run synchronously?

Thanks, P

Upvotes: 3

Views: 2577

Answers (3)

zdan
zdan

Reputation: 29450

How about:

$wmplayer = get-process wmplayer
stop-process $wmplayer.id
wait-process $wmplayer.id -erroraction:silentlycontinue

Note the erroraction is added so you don't get an error when the process is killed quickly,

or as a more handy one-liner:

stop-process -processname wmplayer -passthru| wait-process

Upvotes: 6

Keith Hill
Keith Hill

Reputation: 201652

I'd go with something like this:

calc
calc
calc
Stop-Process -Name calc | 
    Foreach { While ($_ -and !$_.HasExited) { Start-Sleep -milli 300 } }

Upvotes: 0

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74370

Not tested, but you can try:

stop-process -processname wmplayer
get-process | where-object {$_.HasExited}

Upvotes: 0

Related Questions