我正在编写一个 powershell 脚本来压缩文件目录,然后通过 FTP 将其发送到远程位置。 我正在使用 shell 应用程序创建 zip 文件。
我遇到的问题是CopyHere命令立即返回,并且复制发生在不同的线程上。显然,在创建 zip 文件之前我无法开始 FTP 传输。
如何确定 zip 文件创建何时完成?
一些示例代码:
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
$zipSource = $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);
编辑(10年后)
如果您来到此处是因为尝试压缩文件夹,Powershell 现在会提供 Compress-Archive命令行开关。
遗憾的是,对于如何等待 shellApp 方法完成的问题仍然没有答案。
最佳答案
为什么不使用其他同步解决方案,例如 7Zip或PowerShell Community Extenions ? PSCX 围绕 7Zip 提供了一组方便的 cmdlet 包装器。两者都是免费的并且是同步的,例如:
Write-Zip dirToZip dir.zip
关于powershell - 确定 Windows-shell 命令在 Powershell 中完成的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5073225/