簡體   English   中英

等待復制過程完成

[英]Waiting for copy process to finish

在運行另一個命令之前,有什么方法可以等待復制過程完成嗎? 我嘗試了Start-jobWait-Job ,但是它不起作用。

    $func = {
        function move-tozip
        {
        param([string]$filedest)
            $Shell = New-Object -com Shell.Application
            $b = $shell.namespace($zippath.ToString())
            $b.CopyHere($filedest.tostring())
            #Remove-Item -Path $filedest
        }
    }
start-job -InitializationScript $func -ScriptBlock {move-tozip $args[0]} -ArgumentList $file

等待作業完成的最簡單方法是為其命名,並告訴Wait-Job等待具有該名稱的任務,您的腳本將等待名稱為WaitForMe的作業完成,然后運行其余的代碼一旦擁有。

在下面的代碼中使用-Name參數:

$func = 
{
    function Move-ToZip
    { 
      Param([string[]]$path, [string]$zipfile)

      if (-not $zipfile.EndsWith('.zip')) {$zipfile += '.zip'} 

      if (-not (test-path $zipfile))
      { 
        set-content $zipfile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
      }

      $shell = (new-object -com shell.application).NameSpace($zipfile) 

      foreach($file in $path)
      {
        $shell.CopyHere($file)
        start-sleep -milliseconds 100
      }
    } 
}


Start-Job -Name "WaitForMe" -InitializationScript $func -ScriptBlock {Move-ToZip -path $args[0] -zipfile $args[1]} -ArgumentList "D:\data.log", "D:\datazip.zip"

Write-Host "Waiting for job to complete"

Wait-Job -Name "WaitForMe"

Write-Host "Job has completed :D"

壓縮一個文件或文件夾

-ArgumentList "D:\testfile.log", "D:\datazip.zip"

壓縮多個文件或文件夾

-ArgumentList @("D:\testfile.log","D:\testFolder1"), "D:\testzip.zip"

編輯17/12/2015

我已經將此MSDN博客中的代碼改編為Move-ToZip函數,因為以前的代碼根本不適合我,我已經在文件和文件夾上成功測試了上述代碼。 我尚未測試此方法的性能,如果您希望壓縮/壓縮多個大文件/文件夾,我強烈建議您使用已知的工作庫或第三方實用程序(例如7zip)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM