【问题标题】:powershell: synchronous stop-processpowershell:同步停止进程
【发布时间】:2010-11-09 03:29:50
【问题描述】:

好的。 我想停止正在运行的进程,然后在进程停止后继续执行脚本

例如:停止媒体播放器,然后删除媒体播放器数据库(如果你有 wmp12 你可能明白原因!) 但脚本的其余部分会在应用程序有时间关闭之前开始执行。

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

我得到:

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.

我可以强制它同步运行吗?

谢谢, P

【问题讨论】:

    标签: powershell


    【解决方案1】:

    怎么样:

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

    注意添加了erroraction,所以当进程被快速杀死时你不会收到错误,

    或者作为更方便的单行:

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

    【讨论】:

    • 我喜欢你的单行但stop-process 应该使用-PassThru 否则它什么都不返回。
    • 在第一个示例中,如果 stop-process 工作得很快,wait-process $wmplayer.id 将出错/失败。
    【解决方案2】:

    未测试,但您可以尝试:

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

    【讨论】:

      【解决方案3】:

      我会选择这样的:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多