0

This powershell command works perfectly to copy and extract a zip file across two directories:

$shell = New-Object -COM Shell.Application
$target = $shell.NameSpace('D:\destination\')
$zip = $shell.NameSpace('D:\source\version_*.zip')
$target.CopyHere($zip.Items(), 16)

However I am struggling with a modification to make it select only the latest zip file from the source.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
mayersdesign
  • 5,062
  • 4
  • 35
  • 47

1 Answers1

2

Get the zip file with the most recent modification date in a given directory:

$source = "C:\temp"
$destination = "C:\temp\output"

$zipFile = Get-ChildItem -Path $source -Filter "*.zip" |
               Sort-Object LastWriteTime -Descending |
               Select-Object -First 1

Expand-Archive -Path $zipFile.FullName -DestinationPath $destination

This works by searching for all zip files, sorting them by the modified date descending and then grabbing the "first" one (according to the defined sort order).

I've also used the Expand-Archive command to extract the zip to a specified destination. If you need to copy the zip then that's easy enough using the Copy-Item cmdlet first.


As some commenters have pointed out: Expand-Archive was introduced in version 5 of PowerShell.

However the logic of getting the "latest" file is unchanged and can easily be plumbed in to your existing script:

$zip = $shell.NameSpace($zipFile.FullName)
gvee
  • 16,732
  • 35
  • 50