开发者

Determine when windows-shell command has finished in Powershell

I'm writing a powershell script to compress a file directory and then send it to a remote location via FTP. I'm creating the zip file using the shell application.

The problem I've encountered is that the CopyHere command returns immediately, and the copy happens on a different thread. Obviously, I cannot begin the FTP transfer until zip file is created.

How do I determine when the zip file creation is complete?

Some sample code:

if(test-path($destZipFilePath)) {
    remove-item $destZipFilePath;
}
set-content $destZipFilePath("PK" + [char]5 + [char]6 + ("$([char]0)" * 18));

$shellApp = new-object -com shell.application;
$zipFile = $shellApp.Namespace($destZipFilePath);
$zipSource = $shellApp.Namespace($fullDeployDirectory);

$zipFile.CopyHere($zipSource);
############################################################
# CopyHere is called asynchronously                        #
# I do not know how to determine if it has completed       #
# hence this horrible hack                                 #
############################################################

Start-Sleep -m 10000;

############################################################

$zipFile = $null
$zipSou开发者_如何学Pythonrce = $null
$shellApp = $null

    
#Now we FTP the zipped file to the FTP servers

$ftpDest = "{0}/{1}" -f ($ftpAddress, $zipFileName);
$webClient = New-Object System.Net.WebClient;
$webClient.Credentials = New-Object System.Net.NetworkCredential($userName, $password);
$webClient.UploadFile($ftpDest, $$destZipFilePath);

Edit (10 years later)

If you got here because you are trying to compress a folder, Powershell now provides the Compress-Archive commandlet.

Sadly, still no answer to the question of how to wait for a shellApp method to complete.


Why not use some other synchronous solution like 7Zip or the PowerShell Community Extenions? PSCX provides a convenient set of cmdlet wrappers around 7Zip. Both are free and would be synchronous e.g.:

Write-Zip dirToZip dir.zip


late answer but you could try this

[gc]::collect()
[gc]::WaitForPendingFinalizers()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜