PowerShell – Wait for Compression to Finish

backuppowershellwindows-server-2008

I have written a PowerShell script that zips the contents of a folder and sends it to a server for backup. The issue is that the copy process doesn't wait for the zip process to finish. I have tried using Out-Null and Wait-Process, and nothing seems to be working. Out-Null just doesn't do anything, and Wait-Process tells me that no such process exists. I can't seem to figure out the process name for the Windows Compression. Any help would be greatly appreciated. Below is the part of the code I would like to have paused until it finishes.

function out-zip { 
Param([string]$path) 

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

if (-not (test-path $path)) { 
set-content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
} 
$ZipFile = (new-object -com shell.application).NameSpace($path) 
$input | foreach {$zipfile.CopyHere($_.fullname)} 
} 
gi "C:\File-Backups\Share1" | out-zip C:\File-Backups\transfer\PC1-Backup 

enter image description here

Best Answer

Are you sure that code actually compresses files into a valid zip format? It doesn't look like it does anything useful to me. (edit: Oh it does? Neat!)

Anyway, to answer your question regardless, Out-Null doesn't do anything because it's Out-Null... and Wait-Process doesn't do anything because you are not running a process.

What you want are Powershell Jobs.

Start-Job

http://technet.microsoft.com/en-us/library/hh849698.aspx

Wait-Job

http://technet.microsoft.com/en-us/library/hh849735.aspx

edit 2: Also, it looks like you're using Powershell v3!

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$src_folder = "D:\stuff"
$destfile = "D:\stuff.zip"
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
$includebasedir = $false
[System.IO.Compression.ZipFile]::CreateFromDirectory($src_folder,$destfile,$compressionLevel, $includebasedir )

Put a foreach around the last line in there as appropriate to zip each one of your files, or however you want to do it, then wrap the whole thing as the input to a Start-Job.